#!/bin/bash
cocoadialog='/usr/local/bin/CocoaDialog.app/Contents/MacOS/CocoaDialog'
snap="/Users/fm/Desktop/VisiCutWithCam.app/Contents/MacOS/snap"
process_request()
{
	FILE=snapshot.jpg
	ROTATION=0
	snap="/Users/fm/Desktop/VisiCutWithCam.app/Contents/MacOS/snap"
	# wait for GET
		read line
	# take the snapshot
		$snap >/dev/null 2&>1
	# rotate the image
		if [ "$ROTATION" != "0" ]
		then
			mogrify -rotate "$ROTATION>" $FILE
		fi
	# get file size
		eval $(stat -s $FILE)
	# output an HTTP header
		echo -ne "HTTP/1.0 200 OK\r\n"
		echo -ne "Content-Type: image/jpeg\r\n"
		echo -ne "Content-Length: $st_size\r\n"
		echo -ne "Connection: close\r\n"
		echo -ne "\r\n"	
	#output the file
		cat $FILE
	#process remaining input
	while read line
	do
		echo $line > /dev/null
	done
}
echo "Checking Camera...(PWD: $PWD)"
if $snap > /dev/null
then
	echo "Nothing (PWD: $PWD)" > /dev/null
else
	$cocoadialog msgbox --icon x --informative-text "Please make sure that the camera is plugged in via USB (short cable) and no other application is occupying it" --text "Camera doesn't work" --button1 OK
	exit
fi
{
	PORT=8080
	echo "Starting Webserver. Listening on http://$PORT"
	shutdown()
	{
		echo "Caught SIGTERM"
		echo "removing fifo"
		rm fifo
		exit 0
	}
	rm -f fifo
	mkfifo fifo
	trap 'shutdown' SIGTERM SIGINT
	while :
	do 
		nc -l $PORT < fifo | process_request > fifo
		echo "Request completed."
	done
}&
PID=$!
echo "PID is $PID"
$cocoadialog bubble --title "VisiCut ZingCAM" --text "Found Camera.Starting VisiCut and waiting until it is finished"&
open -W ~/Desktop/VisiCut.app
$cocoadialog bubble --title "VisiCut ZingCAM" --text "VisiCut has stopped.Exiting..."&
echo "killing $PID"
kill $PID
