#!/usr/bin/sh

die() {
	echo "Cha-Control: ConnectionError $1 $2"
	exit 1
}

if test "$#" -ne 4
then	die InternalError "usage: gopher [host] [port] [path] [query]"
fi

host=$1
port=${2:-70}
opath=/${3#"${3%%[!/]*}"}
path0=$(printf '%s\n' "$opath" | "$CHA_LIBEXEC_DIR"/urldec)
path=${path0##/?}
query=$4
t=${path0%%"$path"}
t=${t##?}

if test "$t" = 7 && test -z "$4"
then	exec cat <<EOF
Content-Type: text/html

<!DOCTYPE html>
<h1>Search gopher://$host:$port$opath</h1>
<form><input type=search name=name autofocus></form>
EOF
else	LF='
'
	case $t in
	1|7)	msg="Content-Type: text/gopher$LF";;
	h)	msg="Content-Type: text/html$LF";;
	g)	msg="Content-Type: image/gif$LF";;
	p)	msg="Content-Type: image/png$LF";;
	t|3)	msg="Content-Type: text/plain$LF";;
	?)	msg=;;
	*)	exec cat <<EOF
HTTP/1.0 301 fixup url
Location: /1$opath
EOF
		;;
	esac
	query=$(printf '%s\n' "${query##*=}" | \
		sed 's/\+/ /g' | "$CHA_LIBEXEC_DIR"/urldec)
	tab='	'
	printf '%s\r\n' "$path${query:+"$tab"}${query##*=}" | \
		"$CHA_LIBEXEC_DIR"/nc -m "$msg$LF" "$host" "$port"
fi
