#!/usr/bin/perl

$ENV{PATH} = "$ENV{PATH}:/usr/bin";
$ENV{PATH} = "$ENV{PATH}:/bin";

$imgdir = "/mnt/hd/images";
$camdir = "$imgdir/camera";

    open DEVICES, "/proc/bus/usb/devices";
    undef $/;
    $olddevice = <DEVICES>;
    close DEVICES;


while (1) {
    open DEVICES, "/proc/bus/usb/devices";
    undef $/;
    $device = <DEVICES>;
    close DEVICES;
    if ($device ne $olddevice) {
	$olddevice = $device;
	print "usb device changed.\n";
	system("kill -USR1 `cat /var/run/slideshow.pid`");
	system ("cd $camdir; gphoto2 -P");
	&scale_camera_images;
	system ("killall fbi");
    }
    sleep 10;
}


sub scale_camera_images {
    opendir CAMERA, $camdir;
    @files = readdir CAMERA;
    for $f (@files) {
	if ($f =~ m/jpg/i) {
	    system ("jpegtopnm < $camdir/$f | pnmscale -xysize 1024 768 | pnmtojpeg > $imgdir/$f");
	    unlink ("$camdir/$f");
	    sleep 1; # keep processor from overheating!
	}
    }
}
    
