#!/bin/bash
# Version("2.2.0.1")
# InformationalVersion("2.2.0.1")


RECROOT=/home/recording
LAME=/usr/bin/lame
RECEXT=`expr "$PATH_INFO" : '.*\.\(...\)'`
RECFILE=`expr "$PATH_INFO" : '\(.*\)\....'`
CONVERTED=0

# Functions

function send_404 {
	echo -e "HTTP/1.1 404 Not Found\r"
	echo -e "Content-Type: text/html\r"
	echo -e "\r"
	echo -e "<html><head><title>404 Not Found</title></head><body>\r"
	echo -e "<h1>404 Not Found</h1>\r"
	echo -e "The requested recording - /recording$PATH_INFO - was not found.\r"
	echo -e "</body></html>\r"
	echo -e "\r"
	
}

function send_403 {
	echo -e "HTTP/1.1 403 Forbidden\r"
	echo -e "Content-Type: text/html\r"
	echo -e "\r"
	echo -e "<html><head><title>403 Forbidden</title></head><body>\r"
	echo -e "<h1>403 Forbidden</h1>\r"
	echo -e "<p>The requested recording - /recording$PATH_INFO - is not available.\r</p>"
	echo -e "</body></html>\r"
	echo -e "\r"
	exit 0
}

function send_count {
	FILECOUNT=`ls -l $RECROOT$RECFILE.*|wc -l`
	if [ "$FILECOUNT" -eq "0" ]
		then
		send_404
		exit 0
	else
		echo -e "HTTP/1.1 200 OK\r"
		echo -e "Content-Type: text/plain\r"
		echo -e "\r"
		echo -e "$FILECOUNT\r"
		echo -e "\r"
		exit 0
	fi
}

function send_mp3 {
	echo -e "HTTP/1.1 200 OK\r"
	echo -e "Content-Type: audio/mpeg\r"
	echo -e "\r"
	cat "$RECROOT$RECFILE.$RECEXT"
	echo -e "\r"
	exit 0
}

function send_wav {
	echo -e "HTTP/1.1 200 OK\r"
	echo -e "Content-Type: audio/x-wav\r"
	echo -e "\r"
	cat "$RECROOT$RECFILE.$RECEXT"
	echo -e "\r"
	exit 0
}

function convert_wav {
	# Execute Lame to convert file.
	/usr/bin/lame --preset phone $RECROOT$RECFILE.wav $RECROOT$RECFILE.mp3
	if [ "$?" -eq "0" ]
		then
		rm $RECROOT$RECFILE.wav
		CONVERTED=1
	else
		CONVERTED=0
	fi
}

function handle_mp3 {
	if [ -f $RECROOT$PATH_INFO ]
		then
		# Found so send it
		send_mp3
	elif [ -f $RECROOT$RECFILE.wav ]
		then
		# found wav so try to convert it
		convert_wav
		if [ $CONVERTED -eq 1 ]
			then
			send_mp3
		else
			send_404
		fi
		exit 0
	else
		# Send not found
		send_404
	fi
	exit 0
}

function handle_wav {
	if [ -f $RECROOT$PATH_INFO ]
		then
		send_wav
	else
		send_404
	fi
	exit 0
}

# Main Routine

if [ $QUERY_STRING == "count" ]
then
	send_count
fi

case $RECEXT in
	mp3) handle_mp3;;
	wav) handle_wav;;
esac

# No mp3 or wav request so request forbidden
send_403
exit 0
