#!/bin/sh
# Adapter for the spartan protocol. See: spartan://mozz.us

MAPPED_URI_PORT=${MAPPED_URI_PORT:-300} # default port is 300
MAPPED_URI_PATH=${MAPPED_URI_PATH:-/} # needs / for root
if test "$REQUEST_METHOD" != POST && test "$MAPPED_URI_QUERY" = "input"
then	printf "Content-Type: text/html

<!DOCTYPE html>
<form method=POST action='\"$MAPPED_URI_PATH\"'>
Input text to upload:
<p>
<textarea name=q></textarea>
<p>
<input type=submit>
</form>"
	exit 0
fi
CONTENT_LENGTH=${CONTENT_LENGTH:+$(($CONTENT_LENGTH - 2))} # skip q=
CONTENT_LENGTH=${CONTENT_LENGTH:-0} # if missing, set to 0
{
	printf '%s %d\n' "$MAPPED_URI_HOST $MAPPED_URI_PATH" "$CONTENT_LENGTH"
	tail -c+3 # skip q=
} | "$CHA_LIBEXEC_DIR"/nc "$MAPPED_URI_HOST" "$MAPPED_URI_PORT" | {
	IFS= read -r line
	case $line in
	'2 '*)	ctype=${line#2 }
		printf "Content-Type: %s\n\n" "$ctype"
		# Spartan does something very rude by extending text/gemini
		# for the spartan protocol only. Horrible hack to make it work:
		test "${ctype%
}" = "text/gemini" &&
			sed 's/^=: \([^ ]*\)/=> \1?input/' || cat ;;
	'3 '*)	printf "Status: 301\nLocation: %s\n" "${line#3 }" ;;
	'4 '*)	printf "Status: 403\n\n%s" "${line#4 }" ;;
	'5 '*)	printf "Status: 500\n\n%s" "${line#5 }" ;;
	*)	printf "Cha-Control: ConnectionError InvalidResponse\n"
	esac
}
