#!/bin/sh
# Copyright 2020 Charles E. Lehner
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.  This file is offered as-is,
# without any warranty.

exec 2>>/tmp/gmi.err

if [ -n "$GEMINI_URL" ]; then
	# allow server to serve its own source
	printf '20 text/plain\r\n'
	exec cat "$0"
fi

read req
req=$(echo "$req" | sed 's/\s\+$//')

ip_hash=$(echo "$NCAT_REMOTE_ADDR" | sha256sum | head -c 16)
date=$(date -u +%FT%TZ)
printf "%s %s %s\n" "$date" "$ip_hash" "$req" >>/tmp/gmi.log

case "$req" in
	gemini://celehner.com*|celehner.com*|gemini://localhost*|localhost*)
		req_noproto=${req#gemini://}
		hostname=${req_noproto%%/*}
		path=${req_noproto#*/}
		if [ "$path" = "$req_noproto" ]; then path=; fi
		case "$path" in
			*\?*)
				query=${path#*\?}
				path=${path%%\?*}
				;;
			*)
				unset query
				;;
		esac
		case "$path" in /*);; *) path="/$path";; esac

		case "$path" in
			*.add-backlink)
				url=${req%%.add-backlink*}
				path=${path%%.add-backlink}
				file="./$path"
				if [ -d "$file" ]; then
					file="$file/index.gmi"
				fi
				exec ./add-backlink "$url" "$path" "$query" "$file"
			;;
		esac

		file="./$path"
		if [ -d "$file" ]; then
			if ! case "$file" in */);; *) false; esac; then
				# redirect to add trailing slash
				url="gemini://$hostname$path/${query+?}$query"
				exec printf '30 %s\r\n' "$url"
			fi
			file="$file/index.gmi"
		fi

		if [ -f "$file" ]; then
			if [ -x "$file" -a -z "$GEMINI_URL" ]; then
				case "$file" in */index.gmi)
					GEMINI_URL="$req" exec "$file" "$query"
					;;
				esac
			fi
			case "$file" in
				*gmi) printf '20 text/gemini\r\n';;
				*txt) printf '20 text/plain\r\n';;
				*) printf '20 %s\r\n' "$(file -Lb --mime-type "$file")";;
			esac
			exec cat "$file"
		fi
		if [ -f "$file.redirect" ]; then
			exec cat "$file.redirect"
		fi
		;;
	*)
		exec printf '53 Proxy request refused\r\n'
		;;
esac

printf '51 Not Found\r\n'