#!/usr/bin/awk -f
BEGIN {
	for (i = 0; i <= 255; i++)
		ord[sprintf("%c", i)] = i
}
function escape(str, c, len, res) {
	len = length(str)
	res = ""
	for (i = 1; i <= len; i++) {
		c = substr(str, i, 1);
		if (c ~ /[0-9A-Za-z]/)
			res = res c
		else
			res = res "%" sprintf("%02X", ord[c])
	}
	return res
}

# Rewrite pkg.go.dev => godocs.io
/^https?:\/\/pkg\.go\.dev\/?.*$/ { sub(/pkg\.go\.dev/, "godocs.io") }

# Rewrite twitter.com => nitter.net
/^https?:\/\/twitter\.com.*$/ { sub(/twitter\.com/, "nitter.net") }

# Rewrite youtube.com => yewtu.be
/^https?:\/\/(www\.)?youtube\.com.*$/ { sub(/(www\.)?youtube\.com/, "yewtu.be") }

# Rewrite youtu.be => yewtu.be
/^https?:\/\/youtu\.be.*$/ { sub(/youtu\.be\/?/, "yewtu.be/watch?v=") }

# Rewrite medium.com => scribe.rip
/^https?:\/\/([[:alnum:]]+\.)?medium.com\/.*$/ {
	sub(/([[:alnum:]]+\.)?medium.com/, "scribe.rip")
}

# Treat :8080 as http://localhost:8080
/^:[[:alnum:]]+.*$/ { print "http://localhost" $0; next }

# Treat alpha.alpha/... as an http:// URL
/^([[:lower:]-]+\.)?[[:lower:]-]+\.[[:lower:]-]+\/?.*/ { print "https://" $0; next }

# Open protocol:... directly
/^[[:alpha:]][[:alnum:]+.-]*:.*$/ { print $0; next }

# Keep everything else as it is
{ print escape($0) ; next }
