#!/bin/sh

# title: dmenu_websearch
# license: CC0
# author: Sunur Efe Vural <efe@efe.kim>
# version: Jan 4, 2019 (added surf support)
# 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='firefox' #default browser used when focus is not on a browser
bookmarks="$HOME/.bookmarks" #url per line, right of space is ignored
engine='https://duckduckgo.com/lite/?q=%s' #search engine, %s is query
homepage='http://localhost' #page to go when plus sign is selected
uricur="$1" #current uri, if defined replaces plus sign for homepage

gotouri() {
	if [ -z "$shortcut" ] && [ -n "$winid" ] ; then
		xprop -id "$winid" -f _SURF_GO 8s -set _SURF_GO "$choice"
	elif [ -n "$winid" ] ; 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 query to percent encoding and insert it into url
	choice=$(echo "$choice" | hexdump -v -e '/1 " %02x"')
	choice=$(echo "$engine" | sed "s/%s/${choice% 0a}/;s/ /%/g")
	gotouri
}

#get pid for text-browsers and window class for gui browsers
winid=$(xprop -root _NET_ACTIVE_WINDOW | sed 's/.* //')
[ -n "$winid" ] && {
	pid=$(pstree -Al "$(xprop -id "$winid" _NET_WM_PID |\
		awk '{print $3}')" | awk -F "---" '{print $NF}')
	class=$(xprop -id "$winid" WM_CLASS | grep -o '".*"')
}

#get the shortcut that opens the address bar (surf is special snowflake)
case "$class $pid" in
	(*w3m*) shortcut="U" ;;
	(*Luakit*|*Qutebrowser*|*Uzbl*|*Vimb*) shortcut="o" ;;
	(*Links*|*lynx*|*links*|*Conkeror*) shortcut="g" ;;
	(*Firefox*|*Chromium*|*Vivaldi*|*Opera*|*Chrome*|*Netsurf*\
		|*Epiphany*|*Midori*|*Dillo*|*Konqueror*|*Brave*|*Palemoon*\
		|*Arora*|*Iceweasel*|*Icecat) shortcut="ctrl+l" ;;
	(*Surf*) uricur=$(xprop -id "$winid" _SURF_URI |\
		sed 's/.*\"\(.*\)\".*/\1/') ;;
	(*) winid="" ;;
esac

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

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