#!/usr/local/bin/perl
##############################################################################
# You can reach the author under fed@icc.ru
#
# crontab entry should look like follows, in order to save pictures in
# archive at 0th minute of each hour:
# 0 * * * * /usr/bin/nice /home/nautilus/www/webcam/webcam.pl >> /home/nautilus/www/webcam/older/archive.log 
##############################################################################
#
# change this according to your installation

$basedir = "/export/home/nautilus/www/webcam";
$olderdir = '/export/home/nautilus/www/webcam/older';
$latest = "webcam.jpg";		# file updated by the webcam
#$ENV{'TZ'} = 'Asia/Irkutsk';	# POSIX.1 timezone of your webcam
				# not always available
$ENV{'TZ'} = 'MSK-8MSD,M3.5.0,M10.5.0'; # manual timezone


use File::stat;
use Time::localtime;

$file = "$basedir/$latest";

# check if the picture file is there
if (not -r $file) {
    print ctime(time), "  File not found: $file\n";
    exit;
}
if (not -r "$olderdir/latest.jpg") {
    print ctime(time), "  Error: $olderdir must exist and include latest.jpg\n";
    exit;
}

if (stat($file)->mtime == stat("$olderdir/latest.jpg")->mtime) {
    print ctime(time), "  No new picture arrived. Exiting\n";
    exit(0);
}
print ctime(time), "  Copying latest picture to archive\n";
&copy($file, "$olderdir/latest.jpg");
$name = ctime(stat("$olderdir/latest.jpg")->mtime);
$name = substr($name, 4, 15);
$name =~ s/ /-/g;	# replacing all blanks with -
$name =~ s/\://g;       # removing all : 
&copy($file, "$olderdir/$name".'-localtime.jpg');
exit(0);


##################################################################
# This subroutine copies the files

sub copy {
  local($source,$out) = @_;
  if (open(IN,$source)) {
    binmode(IN);
    $/ = undef; $entire_file = <IN>; close(IN);
    open(OUT,">$out") || warn("Cannot create output file $out - $!\n");
    binmode(OUT);
    print OUT $entire_file; close(OUT);
    $mtime = stat( $source)->mtime;
    utime($mtime,$mtime,$out);  # Copy the creation date
  } else {
    warn("Could not open input file $source - $!\n");
  }
}
