#!/usr/bin/env awk -f

BEGIN {
    for (i = 0; i <= 255; i++)
        ord[sprintf("%c", i)] = i
    bangsfile = ENVIRON["XDG_DATA_HOME"] "/bangs"
    while (getline <bangsfile) bangs[$1] = $2
    close(bangsfile)
}
function escape(str, c, len, res, i) {
    len = length(str)
    res = ""
    for (i = 1; i <= len; i++) {
        c = substr(str, i, 1);
        res = res (c ~ /[0-9A-Za-z]/ ? c : "%" sprintf("%02X", ord[c]))
    }
    return res
}

function hexdigit(c) {
    c = toupper(c)
    if (c ~ /^[0-9]$/) return c + 0
    if (c ~ /^[A-Z]$/) return ord[c] - ord["A"] + 10
    else return ""
}

function unescape(str, c, len, res) {
    len = length(str)
    res = ""
    for (i = 1; i <= len; i++) {
        c = substr(str, i, 1);
        if (c == "%")
            c = sprintf("%c", hexdigit(substr(str, ++i, 1)) * 16 \
                    + hexdigit(substr(str, ++i, 1)))
        res = res c
    }
    return res
}

# Piece of shit, fuck off
/^https:\/\/duckduckgo[^\/]*\/l\/\?uddg=/ {
    sub(/^.*\?uddg=/, "")
    sub(/&rut=[0-9a-f]*$/, "")
    $0 = unescape($0)
}

# pkg.go.dev => godocs.io, twitter.com => twitt.re
# youtube.com => yewtu.be, medium.com => scribe.rip,
# reddit.com => teddit.net
/^https?:\/\/pkg\.go\.dev\/?.*$/ { sub(/pkg\.go\.dev/, "godocs.io") }
/^https?:\/\/twitter\.com.*$/ { sub(/twitter\.com/, "twitt.re") }
/^https?:\/\/(www\.)?youtube\.com.*$/ {
    sub(/(www\.)?youtube\.com/, "yewtu.be")
}
/^https?:\/\/youtu\.be.*$/ { sub(/youtu\.be\/?/, "yewtu.be/watch?v=") }
/^https?:\/\/(old\.|www\.)?reddit.com.*$/ {
    sub(/(old\.|www\.)?reddit.com/, "teddit.net")
}
/^https?:\/\/([[:alnum:]]+\.)?medium.com\/.*$/ {
    sub(/([[:alnum:]]+\.)?medium.com/, "scribe.rip")
}
/^https?:\/\/doi.org\// {
    $0 = "https://sci-hub.ru/" unescape($0)
}

# Bangs
/^!/ {
    search = $0
    sub(/^[^ ]* /, "", search);
    $0 = bangs[$1]
    sub(/\{\{\{s\}\}\}/, escape(search))
}

# Open protocol:... directly
/^[a-zA-Z][a-zA-Z0-9+.-]*:[^ ]*$/ { print $0; system(""); next }

# Treat :8080 as http://localhost:8080
/^:[0-9]+.*$/ { print "http://localhost" $0; system(""); next }

# Hacky attempt at a URL regex
/^([a-zA-Z0-9]+\.)+[a-zA-Z0-9]+(\/[^ ]*)?$/ { print "http://" $0; system(""); next }

# IPv4 Addresses
/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+[:\/].*$/ { print "http://" $0; next }

# Open everything else as a search
{ print "https://duckduckgogg42xjoc72x3sjasowoarfbgcmvfimaftt6twagswzczad.onion/html/?q=" escape($0); system(""); next }
