#!/bin/sh

# title: dmenu_websearch
# license: CC0
# author: Sunur Efe Vural <efe@efe.kim>
# version: Feb 6, 2019 (don't use xdotool where possible)
# 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 --new-window'
bookmarks="$HOME/.bookmarks"
homepage='http://localhost'
engine='https://duckduckgo.com/?q=%s'

gotouri() {
	if [ "$browser" = surf ]
	then
		xprop -id "$winid" -f _SURF_GO 8s -set _SURF_GO "$choice"
	elif [ -n "$winid" ] && [ -z "$browser" ]
	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/[[:space:]]/%/g")
	gotouri
}

winid=$(xprop -root _NET_ACTIVE_WINDOW | sed 's/.*[[:space:]]//')
[ -n "$winid" ] &&
	class=$(xprop -id "$winid" WM_CLASS | awk -F'\"' '{ print $(NF - 1) }')

[ -n "$class" ] && case "$class" in
	Firefox) browser='firefox' ;;
	IceCat) browser='icecat' ;;
	Chromium) browser='chromium' ;;
	Chrome) browser='chrome' ;;
	Opera) browser='opera' ;;
	Vivaldi) browser='vivaldi' ;; # not tested
	Brave) browser='brave' ;; # not tested
	Conkeror) browser='conkeror' ;; # not tested
	Palemoon) browser='palemoon' ;; # not tested
	Iceweasel) browser='iceweasel' ;; # not tested
	qutebrowser) browser='qutebrowser' ;;
	Midori) browser='midori' ;; # not perfect but better than using xdotool
	Luakit) browser='luakit' ;; # uses the last window instance
	Uzbl|Vimb) browser='' ; shortcut='o' ;;
	Links) browser='' ; shortcut='g' ;;
	Netsurf*|Epiphany|Dillo|Konqueror|Arora) browser='' ; shortcut='ctrl+l' ;;
	Surf) browser='surf' ; uricur=$(xprop -id "$winid" _SURF_URI |\
			awk -F'\"' '{ print $( NF - 1 ) }') ;;
	*) wmpid=$(xprop -id "$winid" _NET_WM_PID | awk '{ print $3 }')
		pid=$(pstree -ATl "$wmpid" | awk -F'---' '{ print $NF }') ;;
esac

[ -n "$pid" ] && case "$pid" in
	w3m) browser='' ; shortcut="U" ;;
	lynx|links|elinks) browser='' ; shortcut="g" ;;
	(*) winid="" ;;
esac

choice=$(sed "/^#/d;1i${1:-+}" "$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 '{ print $1 }')
	gotouri
else searchweb
fi