#!/bin/sh
# Simple little web server.
PORT=80
DOCROOT=/var/log

log () {
	logger -t httpd "$@"
}

run_nc () {
	nc -p $PORT -l -e $1 </dev/null >/dev/null 2>/dev/null &
}

header () {
	echo "HTTP/1.0 $1 $2"
	echo "Content-Type: $3"
	echo
}

if [ -z "$HTTPD_STARTED" ]; then
	[ -f /var/lib/httpd_stop ] && exit
	HTTPD_STARTED=1
	export HTTPD_STARTED
	# daemonize
	run_nc $0
	exit
else
	# start up the next listener process
	[ -f /var/lib/httpd_stop ] || run_nc $0
fi

read GET page x y z
page="$(echo "$page" | sed 's/[^-.A-Za-z0-9_]//g')" # security; note no subdirs

# Reading the rest of the client's request is important; clients tend to get
# confused otherwise. Junk it all..
while read xx ; do
	test "${xx}" || break
	test "${xx}" = "
" && break
done

if [ -d "$DOCROOT/$page" ]; then
	header 200 OK "text/html"
	echo "<html><head><title>Debian-installer logs and screenshots</title></head><body>"
	echo "<b>Debian-installer logs and screenshots</b><br><br><ul>"
	for file in $(cd "$DOCROOT/$page"; find -type f 2>/dev/null | sed 's/^\.\///' | sort); do
		echo "<li><a href=\"$file\">$file</a>"
	done
	echo "</ul></body></html>"
elif [ -e "$DOCROOT/$page" ]; then
	if [ "${page%.ppm}" != "$page" ]; then
		header 200 "OK" "image/x-portable-pixmap"
	elif [ "${page%.png}" != "$page" ]; then
		header 200 "OK" "image/x-png"		
	else
		header 200 "OK" "text/plain"
	fi

	if ! cat "$DOCROOT/$page" 2>/dev/null; then
		echo "error!"
	fi
else
	header 404 "Not Found" "text/plain" 
	echo "File not found."
fi
