#!/bin/bash

NAME=$1
SERVER_IP=192.168.1.66
PORT=8080
USERNAME=admin
PASSWORD="123456"
CAMERAS="0 1 2 3 4 5 6 7 8 9"
# the real values _will_ differ depending on the machine running the script !!!
SECONDS_PER_FILE=60
OVERLAP_PER_FILE=2

PIDFILE_BASE=/tmp/wget_script.$RANDOM.pids
if [ -z "$NAME" ]; then
	NAME=0
fi
CAPTURE_DIR="$( dirname "${BASH_SOURCE[0]}" )/capture"
mkdir -p $CAPTURE_DIR
cd $CAPTURE_DIR

SHUTDOWN_IN_PROGRESS="false"
quit() {
	if [ "$SHUTDOWN_IN_PROGRESS" == "false" ]; then
		SHUTDOWN_IN_PROGRESS="true"
		echo "quitting..."
		PIDS="$(cat ${PIDFILE_BASE}_A 2>/dev/null) $(cat ${PIDFILE_BASE}_B 2>/dev/null)"
		rm -f ${PIDFILE_BASE}_A ${PIDFILE_BASE}_B
		kill $PIDS 2>/dev/null || (echo "waiting for remaining proccesses..."; sleep 10; echo "killing remaining proccesses..."; kill -9 $PIDS 2>/dev/null)
		exit $1
	fi
}

trap 'quit 0' SIGINT SIGTERM EXIT

do_record() {
	for i in $CAMERAS; do
		echo "starting recording for camera $i" >&2
		OUTFILE_START=tmp_dump_cam_${i}_$(date +%s.%N)_RANDOM$RANDOM.mjpg
		( 
			EXACT_START_TIME=$(date +%s.%N)
			outfile_close_trap() {
				echo "finishing capture file for camera $i"
				EXACT_END_TIME=$(date +%s.%N)
				if [ -f $OUTFILE_START ]; then
					mv $OUTFILE_START dump_cam_${i}_${EXACT_START_TIME}_${EXACT_END_TIME}.mjpg
				fi
			}
			trap outfile_close_trap SIGINT SIGTERM EXIT
			wget --ignore-length --http-user=$USERNAME --http-passwd=$PASSWORD  http://${SERVER_IP}:$PORT/cam/$i/stream.mjpeg -O $OUTFILE_START -q 2>&1 >> /dev/null &
			THIS_WGET_PID=$!
			echo $THIS_WGET_PID >> ${PIDFILE_BASE}_${1}
			wait $THIS_WGET_PID
		) &
	done
}	

while true; do
	if [ ! -z "$PIDS_A" ]; then kill -9 $PIDS_A 2>/dev/null; fi
	echo "starting group A"
	do_record A
	PIDS_B="$(cat ${PIDFILE_BASE}_B 2>/dev/null)"
	if [ ! -z "$PIDS_B" ]; then
		$OVERLAP_PER_FILE
		echo "killing group B"
		kill $PIDS_B 2>/dev/null
		sleep $(($SECONDS_PER_FILE - $OVERLAP_PER_FILE))
	else
		sleep $SECONDS_PER_FILE
	fi

	if [ ! -z "$PIDS_B" ]; then kill -9 $PIDS_B 2>/dev/null; fi
	echo "starting group B"
	do_record B
	PIDS_A="$(cat ${PIDFILE_BASE}_A 2>/dev/null)"
	if [ ! -z "$PIDS_A" ]; then
		sleep $OVERLAP_PER_FILE
		echo "killing group A"
		kill $PIDS_A 2>/dev/null
		sleep $(($SECONDS_PER_FILE - $OVERLAP_PER_FILE))
	else
		sleep $SECONDS_PER_FILE
	fi
done

quit 1
