summaryrefslogtreecommitdiff
path: root/surf-menu
blob: 59dcc300bbd546705407bd76efb304c08c1aca78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/bin/sh
set -e

BOOKMARDS=~/notes/bookmarks.md
# TODO history
#HISTORY=~/notes/.surf_history

set_uri() {
	if [ -n "$XID" ]; then
		xprop -id "$XID" -f "_SURF_GO" 8s -set "_SURF_GO" "$1"
	else
		surf "$1" &
	fi
}

run() {
	if echo "$1" | grep -qE '^\?'; then # We do search on duckduckgo

		set_uri "https://duckduckgo.com/?q=${L#?}&t=surf&kk=-1&ia=web"

	elif echo "$1" | grep -qE '^~?/'; then # This is local path

		set_uri "${1/#\~/$HOME}"

	elif echo "$1" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+'; then # This ipv4 address

		set_uri "$1"

	# TODO ipv6 address

	else # We follow address

		LPROTOCOL="$(echo "$1" | sed -n 's#^\([^:]*\)://.*#\1#p')"
		LHOST="$(echo "$1" | sed -n 's#^[^:]*://##;s#^\([^/]\+\)/\?.*#\1#p')"
		LPATH="$(echo "$1" | sed 's#^[^:]*://##;s#^[^/]\+/\?##')"

		if ! getent hosts "$LHOST" >/dev/null; then
			if getent hosts "$LHOST.cz" >/dev/null; then
				LHOST="$LHOST.cz"
			elif getent hosts "$LHOST.org" >/dev/null; then
				LHOST="$LHOST.org"
			elif getent hosts "$LHOST.com" >/dev/null; then
				LHOST="$LHOST.com"
			fi
			# TODO what to do when we can't expand it?
		fi
		# Decide on protocol (if connection to 443 is not possible then use http otherwise https)
		if [ -z "$LPROTOCOL" ]; then # We already have protocol (given explicitly)
			if nc -z -w1 "$LHOST" 443 2>/dev/null; then
				LPROTOCOL="https"
			else
				LPROTOCOL="http"
			fi
		fi

		set_uri "$LPROTOCOL://$LHOST/$LPATH"

	fi
}

XID=""
ADDCH=""

while [ $# -gt 0 ]; do
	case "$1" in
		-h|--h)
			echo "This is menu script for surf web browser."
			echo "Usage: $0 [OPTION]..."
			echo
			echo "Options:"
			echo "  --help, -h"
			echo "    Print this help text."
			echo "  --xid XID"
			echo "    Instead of opening new surf instance set url to existing one"
			exit
			;;
		--xid)
			XID="$2"
			shift
			;;
		-a|--add)
			shift
			ADDCH="$ADDCH
$1"
			;;
		*)
			echo "Unknown option $1" >&2
			exit 1
			;;
	esac
	shift
done

# If XID is given then as first one add current uri
if [ -n "$XID" ]; then
	ADDCH="$(xprop -id "$XID" _SURF_URI | sed 's/.*= "\(.*\)"/\1/')"
fi

# Note: Bookmarks starts with '* '
CHOOSE="$ADDCH
$(sed -n 's/\* //p' "$BOOKMARDS")"

echo "$CHOOSE" | sed '/^\s*$/d' | dmenu -p 'surf' | while read L; do
	run "$L"
done