#!/bin/sh
# copyright Solene Rapenne <solene@perso.pw>
# insert the MIT license here

go() {
	echo $@
	printf "${1}\r\n" | nc -T noverify -c $2 $3
}
usage() {
	printf "usage: $0 server port url\n\n"
	printf "first line of visit or dl will be used\n"
	printf "choice 1) save line to ./visit to load and open it\n"
	printf "choice 2) save line to ./dl to download it and redisplay menu\n"
	printf "you can save a line using xW visit or xW dl with x being the line number\n"
	printf "Example:\n"
	printf "         show buffer: ,n [enter]\n"
	printf "         visit 5th line as a link: 5W visit [enter] Q [enter]\n"
	exit 0
}

if [ $# -ne 3 ]; then usage ; fi

TMPFILE=$(mktemp /tmp/gophered.XXXXXXXXXXXXXXXXXXX)

go "$1" "$2" "$3" > $TMPFILE
ed $TMPFILE
while [ -f visit ] || [ -f dl ]
do
	if [ -f visit ]
	then
		LINE=$(head -n 1 visit)
		rm visit
		URL=$(echo "$LINE" | cut -d ' ' -f 2)
		HOST=$(echo "$URL" | sed 's,gemini://,,' | cut -d '/' -f 1 | cut -d ':' -f 1)
    		PORT=$(echo "$URL" | sed 's,gemini://,,' | cut -d '/' -f 1 | awk -F ':' '{ if(NF == 1) { print 1965 } else { print $NF }}' )
		echo $URL
		echo $HOST
		echo $PORT
		go "$URL" "$HOST" "$PORT" > $TMPFILE
		ed $TMPFILE
	else
		if [ -f dl ]
		then
			LINE=$(head -n 1 dl)
			rm dl
        		URL=$(echo "$LINE" | cut -d ' ' -f 2)
        		HOST=$(echo "$URL" | sed 's,gemini://,,' | cut -d '/' -f 1 | cut -d ':' -f 1)
        		PORT=$(echo "$URL" | sed 's,gemini://,,' | cut -d '/' -f 1 | awk -F ':' 'NF == 1 { print 1965 } else { print $NF }' )
			DIR_RESOURCE=$(dirname $RESOURCE)
			echo "Download $RESOURCE in ${HOST}${RESOURCE}"
			mkdir -p "$HOST/$DIR_RESOURCE"
			go "$URL" "$HOST" "$PORT" > "${HOST}${RESOURCE}"
			ed $TMPFILE
		fi
	fi
done