#!/usr/bin/sh
# Finger protocol adapter for Chawan.

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

if test "$#" -ne 3
then	die InternalError "usage: finger [host] [port] [path]"
fi

host=$1
port=${2:-79}
path=$3
test "$port" = 79 || die InvalidURL "wrong port, only port 79 is supported"

# Parse the URL. Roughly based on Lynx finger URL parsing, but less
# sophisticated.
if test -z "$REMOTE_USER"
then	case "$path" in
	/w/*)	REMOTE_USER="/w ${path#/w/}" ;;
	*)	REMOTE_USER=${path#/} ;;
	esac
fi

# Headers.
printf 'Content-Type: text/plain\n'

# Newline; from here on we are sending the content body.
printf '\n'

# Finger request, the output of which goes to stdout.
printf '%s\r\n' "$REMOTE_USER" | "$CHA_LIBEXEC_DIR"/nc "$host" "$port"
