#!/usr/bin/perl
#
# This script will grab frames from my web cam at a rate of 1 per second.
# It plants them into directories named after the current date and will also
# delete captures more than a week old
#

use strict;
use Date::Calc qw(Add_Delta_YMDHMS);

my $parent_dir='/gdata/surveillance';
my $cam_name='alley1';

while ( 1 == 1 )
{
	#get the date in the appropriate format
	my $DAY;
	my $MONTH;
	my $YEAR;
	my $HOUR;
	($HOUR, $DAY, $MONTH, $YEAR,) = (localtime)[2,3,4,5];
	#put the date in the right format
	$YEAR = $YEAR + 1900;
	$MONTH = $MONTH + 1;
	if ( $HOUR < 10 )
	{
		$HOUR="0$HOUR";
	}
	if ( $DAY < 10 )
	{
		$DAY = '0'.$DAY;
	}
	if ( $MONTH < 10 )
	{
		$MONTH = '0'.$MONTH;
	}
	my $current_day = "$YEAR".'-'."$MONTH".'-'."$DAY";

	#and now subtract 7 days as we only want to keep vids that are a less
	#than a week old
	($YEAR,$MONTH,$DAY, $HOUR, my $MIN, my $SEC) = Add_Delta_YMDHMS($YEAR,$MONTH,$DAY,$HOUR,'0','0','0','0','-7','0','0','0');

	if ( $MONTH < 10 )
	{
		$MONTH = '0'.$MONTH;
	}
	if ( $DAY < 10 )
	{
		$DAY = '0'.$DAY;
	}

	my $expired_dir= "$YEAR".'-'."$MONTH".'-'."$DAY";

	system("mkdir -p ${parent_dir}/${cam_name}/${current_day}"); 
	system("wget http://guest:guest\@cam.joewise.com/Jpeg/CamImg.jpg -O ${parent_dir}/${cam_name}/${current_day}/`date +%F-%H:%M:%S:%N`_alley1.jpg");
	system("rm -r ${parent_dir}/${cam_name}/${expired_dir}");
	sleep 1;
}
