#!/usr/bin/perl -w

use strict;
use CGI qw(:standard);
use Image::Magick;

# CHANGEME - location of image directories
my @IMAGEDIRS = ('/dir1/dir2/', '/dir3/dir4' ... etc ...);

# default maximum image sizes
my $MAXWIDTH = 800;
my $MAXHEIGHT = 600;

my $TIMEOUT = 10;

#### check the function
my $p_function = defined(param('function')) ?  param('function') : '';
my $p_device = defined(param('device')) ?  param('device') : '';

if ($p_function eq 'picture')
{
    my $maxWidth = $MAXWIDTH;
    my $maxHeight = $MAXHEIGHT;
    if ($p_device eq 'tablet')
    {
        $maxWidth = 800;
	$maxHeight = 405;
    }
    chdir $IMAGEDIRS[rand($#IMAGEDIRS)];;

    # change this section according to the hierarchy in which you store photos
    my @sub1Dirs = <*>;
    my $sub1Dir = '';
    while ($sub1Dir !~ /^\d+\d+\d+\d+$/)
    {
        $sub1Dir = @sub1Dirs[rand($#sub1Dirs)];
    }
    chdir $sub1Dir;
    
    my @sub2Dirs = <*>;
    my $sub2Dir = @sub2Dirs[rand($#sub2Dirs)];
    chdir $sub2Dir;
    
    my @pictures = <*.jpg>;
    my $picture = @pictures[rand($#pictures)];

    # get the image and scale it to suit
    my $image = new Image::Magick;
    my $imageError;
    #if (0) # for testing
    if (!($imageError = $image->Read($picture)))
    {
	my $imgWidth    = $image->Get('width');
	my $imgHeight   = $image->Get('height');
	my $scaleWidth  = $maxWidth / $imgWidth;
	my $scaleHeight = $maxHeight / $imgHeight;
	my $scale       = $scaleHeight < $scaleWidth ? $scaleHeight : $scaleWidth;
	my $imgNewWidth  = int($imgWidth * $scale);
	my $imgNewHeight = int($imgHeight * $scale);
	$image->Resize(width=>$imgNewWidth, height=>$imgNewHeight);

	print "Content-type: image/jpeg\n\n";
	binmode STDOUT;
	my @imageBlobs = $image->ImageToBlob();
	print $imageBlobs[0];
    }
    else
    {
        print "Content-type: text/plain\n\nERROR $imageError!\n";
    	print "sub1Dirs list is " . join (', ', @sub1Dirs) . "\n";
    	print "sub1Dir chosen was $sub1Dir\n";
    	print "sub2Dirs list is " . join (', ', @sub2Dirs) . "\n";
    	print "sub2Dir chosen was $sub2Dir\n";
    	print "picture list is " . join (', ', @pictures) . "\n";
    	print "picture file name is '$picture' \n";
    	#print "image was $imgWidth x $imgHeight\n";
    	#print "image should have been scaled by $scale to $imgNewWidth x $imgNewHeight\n";
    }

}
else
{
    print "Content-type: text/html\n\n";

    print "<html><head>\n<meta http-equiv=\"refresh\" content=\"$TIMEOUT\">";
    print "<img src=\"?function=picture";
    print "&device=$p_device" if ($p_device ne '');
    
    print "\" />";

    print "</body>\n</html>\n";
}
