#!/bin/sh -e

. /env

# run from inetd, e.g.:
# 444	stream	tcp	nowait	www	/x/wwwproxy

AGENT="Mozilla/5.0 (X11; U; Linux i586; en-US; rv:1.5) Gecko/20031007 Firebird/0.7"

cd /var/wwwproxy

read line
req=${line%% *}
line=${line#* }
addy=${line%% *}
proto=${line#* }

perl -ne '/^[\r\n]*$/ && exit'

# work out filename
file="$addy"
test="${file#*://}"
test1="${test%/*}"
if [ "$test" = "$test1" ]; then
	file="$file/"
fi
case "$file" in
*/)
	file="${file}index.html"
	;;
esac

case "$file" in
*.[pP][nN][gG]|*.[jJ][pP][eE][gG]|*.[jJ][pP][gG]|*.[gG][iI][fF])
	# skip it
	;;
http://*|https://*|ftp://*)
	mkdir -p "`dirname "$file"`"
	if [ \! -f "$file" ]; then
		errors=`mktemp -t wwwproxy`
		wget -U"$AGENT" --save-headers -O"$file" -- "$addy" >"$errors" 2>&1 || {
			echo HTTP/1.0 404 Not Found
			echo Content-Type: text/plain
			echo
			cat "$errors"
		}
		rm "$errors"
	fi
	< "$file" httpfilterhtml htmldebloater
	;;
*)
	echo HTTP/1.0 404 Not Found
	echo
	;;
esac

exit
