aboutsummaryrefslogtreecommitdiff
path: root/local/bin/surf-menu
blob: f4925f8247a42e72c83190d2cda34dc9fba06f8a (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
#!/bin/sh
set -e

BOOKMARDS=~/notes/bookmarks.md

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

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

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

		surf "${1/#\~/$HOME}" &

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

		surf "$1" &

	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#^[^/]\+/\?##')"

		# Try to lookup if it's an real address
		# Note: This is hack because of youtube, nslookup return No answer but
		# exists with 0. So I am checking if it returned more than one address
		# (one address is for dns server).
		if [ "$(nslookup "$LHOST" | grep 'Address:' | wc -l)" -le 1 ]; then # It's a real address
			if nslookup "$LHOST.cz" >/dev/null; then # we can expand it with cz
				LHOST="$LHOST.cz"
			elif nslookup "$LHOST.com" >/dev/null; then # we can expand it with com
				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

		surf "$LPROTOCOL://$LHOST/$LPATH" &

	fi
}

if [ -n "$1" ]; then
	run "$1"
	exit
else
	# Note: Bookmarks starts with '* '
	sed -n 's/\* //p' "$BOOKMARDS" | dmenu -p 'surf' | while read L; do
		run "$L"
	done
fi