#!/bin/sh
#inspired by 'firemenu' by <swindlesmccoop> on github
# BRWMENU:
set -e
DMENU_OPTS="-i -fn monospace:size=12 -nb #151515 -nf #bbbbbb -sb #663300 -sf #eeeeee"
BROWSER="brave-bin"
SWALLOW=""
NOTIFIER="notify-send"  
for cmd in dmenu "$BROWSER"; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
        echo "Error: Required command '$cmd' not found" >&2
        exit 1
    fi
done
CHOICES="YouTube\nGithub\nCodeberg\nIPLeak\nQwant\nDuckDuckGo\nURL"
PROMPT="Where to?"
open_url() {
    if [ -z "$1" ]; then
        $NOTIFIER "Error" "No URL specified" 2>/dev/null || echo "Error: No URL specified" >&2
        exit 1
    fi
    
    if ! $SWALLOW "$BROWSER" "$1" >/dev/null 2>&1; then
        $NOTIFIER "Error" "Failed to open browser with URL: $1" 2>/dev/null || \
        echo "Error: Failed to open browser with URL: $1" >&2
        exit 1
    fi
}
get_input() {
    prompt="$1"
    prefix="$2"
    input=$(printf '' | dmenu $DMENU_OPTS -p "$prompt" 2>/dev/null)
    
    if [ -z "$input" ]; then
        $NOTIFIER "Error" "No input provided" 2>/dev/null || echo "Error: No input provided" >&2
        exit 1
    fi
    
    input=$(printf "%s" "$input" | sed 's/ /%20/g')
    echo "${prefix}${input}"
}
CHOICE=$(printf "$CHOICES" | dmenu $DMENU_OPTS -p "$PROMPT" 2>/dev/null)

case "$CHOICE" in
    Github)
        url=$(get_input "Username & repo:" "https://github.com/")
        open_url "$url"
        ;;
    Codeberg)
        url=$(get_input "Username & repo:" "https://codeberg.org/")
        open_url "$url"
        ;;
    IPLeak)
        open_url "https://ipleak.net"
        ;;
    Qwant)
        query=$(get_input "Search Qwant:" "")
        open_url "https://qwant.com/search?q=$query"
        ;;
    DuckDuckGo)
        query=$(get_input "Search DuckDuckGo:" "")
        open_url "https://duckduckgo.com/?q=$query"
        ;;
    URL)
        url=$(get_input "Enter URL:" "")
        # add https:// if missing
        case "$url" in
            http://*|https://*) ;;
            *) url="https://$url" ;;
        esac
        open_url "$url"
        ;;
    YouTube)
        query=$(get_input "Search YouTube:" "")
        open_url "https://youtube.com/results?search_query=$query"
        ;;
    *)
        $NOTIFIER "Error" "Invalid selection: $CHOICE" 2>/dev/null || \
        echo "Error: Invalid selection: $CHOICE" >&2
        exit 1
        ;;
esac
