#!/bin/bash -e

# proxy_collect_urls 0.1
# written by Sam Watkins, 2009

# proxy_collect_urls simply collects all the urls requested, and returns bogus (empty) files or failure messages

# Run proxy_collect_urls from inetd, e.g. in /etc/inetd.conf:
# 445	stream	tcp	nowait	someuser	/usr/bin/proxy_collect_urls	proxy_collect_urls

# make sure /etc/hosts.allow contains the line:
# ALL: LOCAL

log_file="/var/log/tpkg_proxy"
urls_file="/var/lib/tpkg_proxy/urls"

if [ ! -w "$log_file" ]; then
	echo HTTP/1.0 500 Internal Server Error
	echo Content-Type: text/plain
	echo
	echo "tpkg_proxy's log file is not writable."
	exit
fi

exec 2>>"$log_file"

error() {
	cat "$errors" >>"$log_file"
	echo >>"$log_file"
	echo HTTP/1.0 500 Internal Server Error
	echo Content-Type: text/plain
	echo
	cat "$errors"
#	rm "$errors"
	exit
}

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
http://*.deb|ftp://*.deb) # no https at the moment
	dir="`dirname "$file"`"
	base="`basename "$file"`"
	pkg="${base%%_*}"

	echo "$file" >>"$urls_file"

	echo HTTP/1.0 404 Not Found
	echo
	;;
*)
	echo HTTP/1.0 403 Forbidden
	echo
	;;
esac

cat "$errors" >>"$log_file"
echo >>"$log_file"
#rm "$errors"

exit
