#!/usr/bin/env bash

# -----------------------------------------------------------------------------
# Info:
#   author:    Miroslav Vidovic
#   file:      web-search.sh
#   created:   24.02.2017.-08:59:54
#   revision:  ---
#   version:   1.0
# -----------------------------------------------------------------------------
# Requirements:
#   rofi
# Description:
#   Use rofi to search the web.
# Usage:
#   web-search.sh
# -----------------------------------------------------------------------------
# Script:

declare -A URLS
# Default book search
# https://b-ok.cc/s/?q="
#
URLS=(
	["search"]="https://duckduckgo.com/?q="
	["booty"]="https://thepiratebay.zone/search/"
	["books"]="https://libgen.is/fiction/?criteria=&language=English&format=epub&q="
	["comics"]="https://annas-archive.org/search?lang=en&content=book_comic&ext=&sort=newest&q="
	["amazon"]="https://www.amazon.com/s?k="
	["stackoverflow"]="http://stackoverflow.com/search?q="
	["hoogle"]="https://www.google.com/search?q="
	["code"]="https://searchcode.com/?q="
	["beer"]="https://www.beeradvocate.com/search/?qt=beer&q="
	["ebay"]="https://www.ebay.com/sch/i.html?LH_BIN=1&_nkw="
	["metacritic"]="https://www.metacritic.com/search/all/"
)

# List for rofi
gen_list() {
	for i in "${!URLS[@]}"; do

		echo "$i"
	done
}

urlencode() {
	# urlencode <string>

	local LANG=C
	local length="${#1}"
	for ((i = 0; i < length; i++)); do
		local c="${1:i:1}"
		case $c in
			[a-zA-Z0-9.~_-]) printf "$c" ;;
			*) printf '%%%02X' "'$c" ;;
		esac
	done
}

main() {
	# Pass the list to rofi
	platform=$( (gen_list) | rofi -dmenu -matching fuzzy -no-custom -location 0 -p "Search > ")

	if [[ -n "$platform" ]]; then
		query=$( (echo) | rofi -dmenu -matching fuzzy -location 0 -p "Query > ")

		if [[ -n "$query" ]]; then
			URL=${URLS[$platform]}$(urlencode "$query")
			qutebrowser --target window $URL
		else
			exit
		fi

	else
		exit
	fi
}

main

exit 0
