#!/bin/sh
#
# Basic main sws script written in shell-script
#
#  - pancake at phreaker.net

# Main Defines
HSML=../src/Hsml/hsml
AWK=/usr/bin/awk
MIMEFILE=/etc/mime.types
OS=`echo $(uname && uname -r)`
DATE=`date`

cd ../Exec/htdocs/

# Parse methods
if [ "${METHOD}" = "TRACE" ]; then
	echo "Trying to hack? I think no.";
	exit
fi
if [ "${METHOD}" = "STATUS" ]; then
	echo "TcpWinSize:    $TCPWINSIZE"
	echo "ServerVersion: $VERSION"
	echo "DATE:          $DATE"
	echo "RemoteHost:    $REMOTE_HOST"
	echo "RemoteIP:      $REMOTE_ADDR"
	echo "RemotePort:    $REMOTE_PORT"
	echo "ListenIP:      $LISTEN_ADDR"
	echo "ListenPort:    $LISTEN_PORT"
	echo "Family:        $FAMILY"
	echo "Method:        $METHOD"
else
if [ "${METHOD}" = "GET" ]; then
	ERR=0
	if [ -e "./${FILE}" ]; then
		if [ -d "./${FILE}" ]; then
			if [ -e "./${FILE}/index.html" ]; then
				FILE=${FILE}/index.html
				FILETYPE="html"
			else
				ERR="1";
			fi
		fi
		if [ "${ERR}" = "0" ]; then
			if [ "1.1" = "${HTTP}" ]; then
				printf "HTTP/1.1 200 OK\r\n"
				printf "Date: ${DATE}\r\n"
				printf "Server: Screws/${VERSION} running on ${OS}\r\n"
#			printf "Transfer-Encoding: chunked\r\n"
				printf "Connection: close\r\n"
#				MIME=`${AWK} '{ if (($2==${MIMETYPES})&&($1!~/^#/)) { print $1; }' ${MIMEFILE}`
				MIME=""
				if [ "${MIME}" = "" ]; then
					MIME="text/html"
				fi
				if [ "${FILETYPE}" = "html" ]; then
					printf "Content-Type: ${MIME}; charset=iso-8859-1\r\n"
				fi
#				SIZE=`ls -l ${PWD}/${FILE} | awk '{ print $5; }'`
#				printf "\r\n${SIZE}"
				printf "\r\n"; # Not Chunked
			fi
			if [ ! "${FILETYPE}" = "hsml" ]; then
				HSML="cat"
			fi
			${HSML} "./${FILE}";
#			if [ "1.1" = "${HTTP}" ]; then
#				printf "\r\n\r\n0\r\n\r\n" # note is 0x0A0A
#			fi
		fi
	else
		ERR=1
	fi
	if [ "${ERR}" = "1" ]; then
		if [ "1.1" = "${HTTP}" ]; then
		printf "HTTP/1.1 404 Not Found\r\n"
		printf "Date: ${DATE}\r\n"
		# Must be: Mon, 30 Jun 2003 00:00:32 GMT\r\n"
		printf "Server: Screws/${VERSION} running on ${OS}\r\n"
		printf "Content-Type: text/html; charset=iso-8859-1\r\n"
		#printf "Transfer-Encoding: chunked\r\n"
		printf "Connection: close\r\n"
		# # this is chunked # #
		#printf "\r\n7\r\npancake\r\n\r\n0\r\n\r\n"
		fi
		printf "\r\n<html><b>The requested file '${FILE}' was not found.</b></html>\r\n"
	fi
else
	printf "<html>File <i>\"${FILE}\"</i> not found</html>\r\n";
fi
fi
