#! /bin/ash
#Set your hostname after this variable
readonly PATH=/usr/lib/restricted/bin
readonly fqdn=gopher.zcrayfish.soy
oldfqdn=zcrayfish.dyndns.org

error301 () {
    printf '%s\15\12' "HTTP/1.0 301 Moved Permanently" \
	"Location: https://$fqdn$REQUEST_URI" \
        "Content-Type: text/plain" \
        "Server: gopher to http gateway at $fqdn" \
        "" \
        "HTTP/1.0 301 Moved permanently" \
        "http://$oldfqdn$REQUEST_URI" \
	"Might be found at:" \
	"https://$fqdn$REQUEST_URI" \
        "" \
        "gopher to http gateway at $fqdn"
}

# Gather request and sanitise, not sure if needed now that we're running under lighttpd
filename="$(printf "%s" "$REQUEST_URI" | sed -e 's/%2c/,/gI' -e 's/%20/ /g')"

#old FQDN? Redirect them!
zdo=$(echo "$HTTP_HOST" | grep -i zcrayfish.dyndns.org)
test ! -z "$zdo" && error301 && exit

    #Step4
    case "$filename" in
	/7*httpsearch*)
	    printf '%s\15\12' 'HTTP/1.0 200 OK' \
		'Content-Type: text/html' \
		"Server: gopher to http gateway at $fqdn" \
		'' \
		'<!DOCTYPE HTML PUBLIC "ISO/IEC 15445:2000//DTD HyperText Markup Language//EN">'
            searchytwothousand="$(printf $filename | sed 's/httpsearch=//g')"
	    lynx -anonymous -dump -source "gopher://$fqdn:70$searchytwothousand" | \
		tidyp -in -w 0 -cn --doctype omit --show-errors 0 --show-warnings 0 --quiet 1 --uppercase-tags 1 --uppercase-attributes 1 --char-encoding utf8 | \
		sed -e 's/<A HREF="\/\//<A HREF="gopher:\/\//g' -e 's/<A HREF="gopher:\/\/'$fqdn':70/<A HREF="\/\/'$fqdn'/g' -e '/<HEAD>/a <LINK REL="STYLESHEET" HREF="//gopher.zcrayfish.soy/stylesheet.css">\n<LINK REL="SHORTCUT ICON" HREF="//gopher.zcrayfish.soy/favicon.ico">'
		    ;;

	/7*)
	    printf '%s\15\12' "HTTP/1.0 200 OK" \
		"Content-Type: text/html" \
		"Server: gopher to http gateway at $fqdn" \
		"" \
		'<!DOCTYPE HTML PUBLIC "ISO/IEC 15445:2000//DTD HyperText Markup Language//EN">' \
		'<HTML><HEAD><TITLE></TITLE><LINK REL="STYLESHEET" HREF="//gopher.zcrayfish.soy/stylesheet.css">' \
		'<LINK REL="SHORTCUT ICON" HREF="//gopher.zcrayfish.soy/favicon.ico"></HEAD><BODY>' \
		'<P>This is a searchable gopher index. Enter search keywords below<BR>' \
		"<FORM ACTION='$filename' METHOD='GET'><P><TEXTAREA ROWS='10' COLS='72' NAME='httpsearch'></TEXTAREA><BR><INPUT TYPE='submit'></P></FORM>" \
		'</BODY></HTML>'

#		"<FORM ACTION='$fqdn$filename' METHOD='GET'>" \
#		'<P>This is a searchable gopher index. Enter search keywords below<BR><INPUT TYPE="TEXT" NAME="httpsearch"></P></FORM>' \

	    ;;
#	/debug*)
#	    printf '%s\15\12' "HTTP/1.0 200 OK" \
#		"Content-Type: text/plain" \
#		""
#	    set
#	    ;;
	###START OF DUMB / NON-INTELLIGENT GOPHER TYPES###
	/[04569IMPdghps]*)
	    case "$filename" in
		/0*)
		    mimetype="Content-Type: text/plain"
		    ;;
		/4*)
		    mimetype="Content-Type: application/mac-binhex40"
		    ;;
		/5*)
		    mimetype="Content-Type: application/octet-stream"
		    ;;
		/6*)
		    mimetype="Content-Type: message/rfc822"
		    ;;
		/9*)
		    mimetype="Content-Type: application/octet-stream"
		    ;;
		/I*.webp)
		    mimetype="Content-Type: image/webp"
		    ;;
		/I*)
		    mimetype="Content-Type: image/jpeg"
		    ;;
		/M*)
		    mimetype="Content-Type: message/rfc822"
		    ;;
		/P*)
		    mimetype="Content-Type: application/pdf"
		    ;;
		/d*)
		    mimetype="Content-Type: application/octet-stream"
		    ;;
		/g*)
		    mimetype="Content-Type: image/gif"
		    ;;
		/h*)
		    mimetype="Content-Type: text/html"
		    ;;
		/p*)
		    mimetype="Content-Type: image/png"
		    ;;
		/s*)
		    mimetype="Content-Type: application/octet-stream"
		    ;;
	    esac
	    xyzzy="$(curl -q --disable -s --output - "gopher://$fqdn:70$filename" | base64)"
	    isdumb="true"
	    ;;
	###END OF DUMB / NON-INTELLIGENT GOPHER TYPES###
	*)
		#Store lynx output for future processing
		xyzzy="$(lynx -anonymous -dump -source "gopher://$fqdn:70$filename" | \
		tidyp -in -w 0 --doctype omit --show-errors 0 --show-warnings 0 --quiet 1 --uppercase-tags 1 --uppercase-attributes 1 --char-encoding utf8 | \
		sed -e 's/<A HREF="\/\//<A HREF="gopher:\/\//g' -e 's/<A HREF="gopher:\/\/'$fqdn':70/<A HREF="/g' -f /srv/www/htdocs/head.sed -f /srv/www/htdocs/images.sed )"
		if [ "$mimetype" = "" ]; then
			mimetype="Content-Type: text/html"
		fi
		    ;;
    esac

###OUTPUT SECTION###

#We'll use the output of Lynx or curl to determine if gopher content is 404d
#Non gophermap content may be binary, base64 it so the shell can deal with it
if [ "$isdumb" = "true" ] ; then
  precontent=$(echo "$xyzzy" | base64 -d)
else
  #precontent=$(echo "$xyzzy" | sed -n 's/.*<PRE>\(.*\)<\/PRE>.*/\1/p')
  precontent=$(echo "$xyzzy" | xargs -s 633 | grep -E -o "<PRE>.*?</PRE>")
fi

#See if there's an error
is403=$(echo "$precontent" | head -n1 | grep "Error: Access denied!")
is404=$(echo "$precontent" | head -n1 | grep "Error: File or directory not found!")

#Respond to any errors
if [ -n "$is403" ] ; then
  printf '%s\15\12' 'HTTP/1.0 403 Forbidden' && iserror="true"
fi

if [ -n "$is404" ] ; then
  printf '%s\15\12' 'HTTP/1.0 404 Not Found' && iserror="true"
fi

if [ -n "$iserror" ] ; then
	if [ "$isdumb" = "true" ] ; then
	  printf '%s\15\12' "Content-Type: text/plain" \
  	  '%s\15\12' "Server: gopher to http gateway at $fqdn" \
	  '' \
	  "$precontent"
	else
	  printf '%s\15\12' "Content-Type: text/html" \
  	  '%s\15\12' "Server: gopher to http gateway at $fqdn" \
	  '' \
	  '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' \
	  "$xyzzy"
	fi
  exit
fi

#If no errors, then we go here
printf '%s\15\12' 'HTTP/1.0 200 OK' \
"$mimetype" \
"Server: gopher to http gateway at $fqdn" \
''
if [ "$mimetype" = "Content-Type: text/html" ]; then
	echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'
fi
if [ "$isdumb" = "true" ] ; then
  echo "$xyzzy" | base64 -d
else
  echo "$xyzzy"
fi
echo ""