export LC_ALL=en_US.UTF-8

url="$1"
req="$2"

H1="\e[1;35m"
H2="\e[1;34m"
H3="\e[1;33m"
LINK="\e[0;34m"
QUOTE="\e[2m"
CODE="\e[1;30;47m"
RESET="\e[0m"
URL="\e[2;37m"

urlencode () {
awk 'BEGIN { for (i=0;i<256;i++) hex[sprintf("%c",i)] = sprintf("%%%02X",i)}
{ for (i=1;i<=length($0);i++) { c = substr($0,i,1); if (c ~ /[A-Za-z0-9_.~-]/) printf "%s", c; else printf "%s", hex[c];} printf "\n"; }'
}

gemcolor () { 
awk -v H1="$H1" -v H2="$H2" -v H3="$H3" -v LINK="$LINK" -v QUOTE="$QUOTE" -v CODE="$CODE" -v RESET="$RESET" -v URL="$URL" ' BEGIN { incode = 0; lineno = 0 } /^### / { sub(/^### /, ""); print H3 $0 RESET; next } /^## / { sub(/^## /, ""); print H2 $0 RESET; next } /^# / { sub(/^# /, ""); print H1 $0 RESET; next } /^> / { sub(/^> /, ""); print QUOTE "❯ " $0 RESET; next } /^```/ { incode = !incode; if (incode) { lineno = 0; print CODE; } else { print RESET; } next; } /^=>/ { url=$2; pos = 1; for (i = 1; i < 3; i++) pos += length($i) + 1; text=substr($0, pos); if (text=="") text=url; printf("%s%s%s %s%s%s\n", LINK, text, RESET, URL, url, RESET); next; } { if (incode) { lineno++; printf("%3d | %s\n", lineno, $0); } else { print $0; }}' 
}

server=$(echo "$url" | awk -F'//' '{print $2}' | awk -F'/' '{print $1}')
if [ ! -z "$2" ]; then url="$url?$(printf '%s' "$2" | urlencode)"; fi
echo -e "$url" | ncat -C --ssl --ssl-cert ~/mycert.pem --ssl-key ~/mykey.pem "$server" 1965 | gemcolor
echo
