#!/bin/sh

engine_names="\
alpine_wiki
alternativeto
arch_wiki
archive.org
devhints
duckduckgo
gentoo_wiki
github
gitlab
godoc
google_images
mdn
odysee
open_street_map
searx.be
searx.disroot
searx.ononoki
stackoverflow
thesaurus
twitter
urban_dictionary
vocabulary
wikipedia
wiktionary.en
youtube\
"

query=$(printf "" | {{ launcher }} {{ dmenu_flag }} -p 'Search{{ (launcher == 'fuzzel') | ternary(': ', '') }}' | urlfilter)

if [ -z "${query}" ]; then
	echo "Query is blank."
	exit 1
fi

if printf "%s" "${query}" | grep -qE '^https?://.*$'; then
	xdg-open "${query}"
else
	engine=$(printf "%s" "${engine_names}" | {{ launcher }} {{ dmenu_flag }} -p 'Engine{{ (launcher == 'fuzzel') | ternary(': ', '') }}')
	if [ -n "${engine}" ]; then
		case ${engine} in
			alpine_wiki) engine_url='https://wiki.alpinelinux.org/w/index.php?title=Special%3ASearch&fulltext=Search&search=' ;;
			alternativeto) engine_url='https://alternativeto.net/browse/search?q=' ;;
			arch_wiki) engine_url='https://wiki.archlinux.org/index.php?search=' ;;
			archive.org) engine_url='https://archive.org/search.php?query=' ;;
			devhints) engine_url='https://devhints.io/' ;;
			duckduckgo) engine_url='https://html.duckduckgo.com/html?q=' ;;
			gentoo_wiki) engine_url='https://wiki.gentoo.org/index.php?title=Special%3ASearch&profile=default&fulltext=Search&search=' ;;
			github) engine_url='https://github.com/search?utf8=\u2713&q=' ;;
			gitlab) engine_url='https://gitlab.com/explore?utf8=\u2713&sort=latest_activity_desc&name=' ;;
			godoc) engine_url='https://pkg.go.dev/search?q=' ;;
			google_images) engine_url='https://www.google.com/search?tbm=isch&q=' ;;
			mdn) engine_url='https://developer.mozilla.org/en-US/search?q=' ;;
			odysee) engine_url='https://odysee.com/$/search?q=' ;;
			open_street_map) engine_url='https://www.openstreetmap.org/search?query=' ;;
			searx.be) engine_url='https://searx.be/?category_general=on&q=' ;;
			searx.disroot) engine_url='https://search.disroot.org/?category_general=on&q=' ;;
			stackoverflow) engine_url='http://stackoverflow.com/search?q=' ;;
			thesaurus) engine_url='https://www.thesaurus.com/browse/' ;;
			twitter) engine_url='https://twitter.com/search?q=' ;;
			urban_dictionary) engine_url='https://www.urbandictionary.com/define.php?term=' ;;
			vocabulary) engine_url='https://www.vocabulary.com/dictionary/' ;;
			wikipedia) engine_url='https://en.wikipedia.org/wiki/' ;;
			wiktionary.en) engine_url='https://en.wiktionary.org/wiki/' ;;
			youtube) engine_url='https://www.youtube.com/results?search_query=' ;;

			# Use "searx.ononoki" as the default search engine
			*) engine_url='https://search.ononoki.org/?category_general=on&q=' ;;
		esac

		xdg-open "${engine_url}${query}"
	else
		echo "Search engine name is blank."
		exit 1
	fi
fi
