#!/bin/sh

# title: dmenu_websearch
# license: CC0
# author: Sunur Efe Vural <efe@efe.kim>
# version: Dec 12, 2018
# dependencies: dmenu, xdotool, hexdump, xprop, pstree, setxkbmap...

# A  browser-independent address  bar  with bookmark  support. When  the
# cursor is on a web browser it acts as the address bar of that browser.

browser="st -e w3m"
bookmarks_file=~/.bookmarks #url per line
search_engine="https://duckduckgo.com/lite/?q=%s"
homepage="http://localhost"

openchoice() {
	if [ ! -z "$windowid" ] ; then
		#change layout to us cuz xdotool spasms with non-latin layouts
		layout=$(setxkbmap -query | awk '/^layout:/{ print $2 }')
		setxkbmap -layout us
		xdotool key --clearmodifiers "$shortcut"\
		type --clearmodifiers --delay 2 "$choice"
		xdotool key --clearmodifiers Return
		setxkbmap -layout "$layout"
	else $browser "$choice"
	fi
}

searchweb() {
	#convert search term to percent encoding
	choice=$(echo "$choice" | hexdump -v -e '/1 " %02x"' | sed 's/ 0a$//')
	#insert search term into the search engine url
	choice=$(echo "$search_engine" | sed "s/%s/$choice/;y/ /%/")
	openchoice
}

#get termprocess for text browsers and windowclass for gui browsers.
windowid=$(xprop -root _NET_ACTIVE_WINDOW | awk '{print $5}')
[ -z "$windowid" ] || {
	processid=$(xprop -id "$windowid" _NET_WM_PID | awk '{print $3}')
	termprocess=$(pstree -Al "$processid" | awk -F "---" '{print $NF}')
	windowclass=$(xprop -id "$windowid" WM_CLASS | grep -o '".*"')
}

#get the shortcut that opens the address bar
case "$windowclass $termprocess" in
	(*w3m*) shortcut="U" ;;
	(*Luakit*|*Qutebrowser*|*Uzbl*) shortcut="o" ;;
	(*Links*|*lynx*|*links*|*Conkeror*) shortcut="g" ;;
	(*Firefox*|*Chromium*|*Vivaldi*|*Opera*|*Chrome*|*Netsurf*|*Arora*\
	|*Epiphany*|*Midori*|*Dillo*|*Konqueror*|*Brave*|*Palemoon*\
	|*Iceweasel*|*Icecat) shortcut="ctrl+l" ;;
	(*) windowid="" ;;
esac

choice=$(sed "/^#/d;1i${1:-•}" "$bookmarks_file"\
	| dmenu -i -p "Go:" -w "$windowid") || exit 1
[ "$choice" = "•" ] && choice="$homepage"

if echo "$choice" | grep -EZ "^(ht|f)tp(s?)\:\/\/" ; then
	choice=$(echo "$choice" | awk -F" " '{ print $1 }')
	openchoice
else searchweb
fi
