#!/usr/bin/perl

#cycle_web_images-Cycle images around on the "Calalcade of Mammals" blog.
#
#
#
#Written: 12-04
#Version: .001
#
#Jim Lund, jiml@uky.edu


#
#Global variables.
#
#$SCRIPT = "index.php"; WP Ver 1.2.1
$SCRIPT = "wp-content/themes/default/index.php";
$MATCH= "ID='cavXX'"; #XX is image number.
$IMAGE_COUNT = 5;
$GALLERY = "past/cavalcadeXX.php"; #XX is page number.  First page has no number.
$SOURCE_DIR = "future";
$PAST_DIR = "past";
$QUEUE_FILE = "mammals.txt";
$IMAGE_SIZE = 90;


#
#Check for command line args.
#

for $i (@ARGV) {
    $switch=substr($i,0,2);
#
#First check arguments for 'cry for help'
#
    if ($switch eq "-q") {
        print <DATA>;
        exit(0);
        }

#Interpret remaining arguments

#
#Just resize the next image in the queue.  Used when the automatic software screws up.
#
    if ($switch eq "-i") {
	$image_file=substr($i,2);
	$image_file =~ s/(['"])/\\$1/g;
	&Resize_image($image_file);
	exit;
    }
}



#
#Find next image in rotation order file.
#Each line in the file is tab-delimited.
#File contains ordered list of images, one image per line.  Used images
#get pushed onto the bottom of the file.  A line of '----' separates the
#sections.
#
open(QUEUE,'<'.$QUEUE_FILE) or warn "Can't open file $QUEUE_FILE: $!\n";
my @queue = <QUEUE>;

if ($queue[0] =~ /^------/) {
    warn "No images in queue, aborting!";
    exit;
}

my $next_line = shift(@queue);
chomp $next_line;
my ($new_url,$new_image) = split(/\t/,$next_line);
$new_image =~ s/(['"])/\\$1/g;
push(@queue,$next_line."\n");

close QUEUE or warn "Can't close file $QUEUE_FILE: $!\n";


#
#Write updated file.
#
open(QUEUE,'>'.$QUEUE_FILE) or warn "Can't open file $QUEUE_FILE: $!\n";
print QUEUE @queue;
close QUEUE or warn "Can't close file $QUEUE_FILE: $!\n";

#print STDERR "NEW:$new_url,$new_image\n";

#
#Load in web page.
#
open(HTML,'<'.$SCRIPT) or warn "Can't open web page $SCRIPT: $!\n";
my @page = <HTML>;
close HTML or warn "Can't close web page $SCRIPT: $!\n";



#
#Loop through images to move.
#
my ($bump, $bump_url);
for (my $j=1; $j <= $IMAGE_COUNT;$j++) {

    my $this_match= $MATCH;
    $this_match =~ s/XX/sprintf("%02u",$j)/e;
#print STDERR "M:$this_match\n";
    for (my $i=1; $i <= @page;$i++) {

	if ($page[$i] =~ /$this_match/i) {
	    my ($this_image) = $page[$i] =~ /SRC=["']([^"']+)['"]/i;
	    my ($this_url) = $page[$i] =~ /HREF=["']([^"']+)['"]/i;
#print STDERR "N $j:$this_image,$this_url\n";
	    if ($j == $IMAGE_COUNT) {
	 	#Move last image to past folder and update past page.
		system("mv $this_image $PAST_DIR");
		&Update_past_page($this_url,$this_image);

	    } elsif ($j == 1) {
		#Move new image from future folder to main folder.
		system("mv $SOURCE_DIR/$new_image .");
		&Resize_image($new_image);
		$bump = $new_image;
		$bump_url = $new_url;
	    }

	    #Set image
#print STDERR "BUMP:$bump_url,$bump\n";
	    my ($bump_name,$sci_bump) = &Parse_name($bump);
	    $page[$i] =~ s/SRC=["'][^"']*['"]/SRC="$bump"/i;
	    $page[$i] =~ s/HREF=["'][^"']*['"]/HREF="$bump_url"/i;
	    $page[$i] =~ s/<P>.*?<\/P>/<p>$bump_name<\/p>/i;
	    $bump = $this_image;
	    $bump_url = $this_url;
	 
	    last;
	}
    }
}

#
#Write updated file.
#
open(HTML,'>'.$SCRIPT) or warn "Can't open web page $SCRIPT: $!\n";
print HTML @page;
close HTML or warn "Can't close web page $SCRIPT: $!\n";



#
#End of main section.  Start of subroutines.



sub Update_past_page {
my ($this_url,$this_image) =@_;

my ($name,$sci_name) = &Parse_name($this_image);

$GALLERY =~ s/XX//;

#
#Load in web page.
#
open(HTML,'<'.$GALLERY) or warn "Can't open web page $GALLERY: $!\n";
my @page = <HTML>;
close HTML or warn "Can't close web page $GALLERY: $!\n";


open(HTML,'>'.$GALLERY) or warn "Can't open web page $GALLERY: $!\n";

#
#Find blank in template, add an image.
#
my $all_done=0;
for (my $i=0; $i < @page; $i++) {

    if (!$all_done && $page[$i] =~ /SRC="blank.jpg"/i) {
	$page[$i] =~ s/blank.jpg/$this_image/;
	$page[$i] =~ s/HREF=""/HREF="$this_url"/i;
	$page[$i] =~ s/<P><\/P>/<p>$name<br>$sci_name<\/p>/i;
	$all_done = 1;
#print STDERR "CAV $this_url,$this_image: $page[$i]\n";
    }


#
#Make a new template line from the last table line.
#
    if (!$all_done && $page[$i] =~ /<\/TABLE>/i) {
	my $new_line = $page[$i-1];
	$new_line =~ s/SRC="[^"]+"/SRC="blank.jpg"/ig;
	$new_line =~ s/HREF="[^"]+"/HREF=""/ig;
	$new_line =~ s/<P>.+?<\/P>/<p><\/p>/ig;
#print STDERR "CAV2 $new_line\n";
	splice(@page,$i,0,$new_line);
	$i--;
	next;	#skip printing this time.
    }

    print HTML $page[$i];
}

close HTML or warn "Can't close web page $GALLERY: $!\n";

}

sub Parse_name {
my ($this_image) = @_;

$this_image =~ s/\.(jpg|gif|png|jpeg)$//;

my ($sci_name) = $this_image =~ /^(.+?)__/;
my ($name) = $this_image =~ /__(.+?)$/;

if (!$name) { $name = $this_image; }

$name =~ s/_/ /g;
$sci_name =~ s/_/ /g;

return ($name,$sci_name);
}


sub Resize_image {
my ($image) = @_;

open(IM,"identify $image |") or warn "Can't run ImageMagick process: $!\n";;
my $im = <IM>;
close IM or warn "Can't exit ImageMagick process: $!\n";

my ($x,$y) = $im =~ / (\d+)x(\d+)/;

#print STDERR "XY: $x,$y\n";

#
#Small, don't change it.
#
if ($x <= $IMAGE_SIZE && $y <= $IMAGE_SIZE) { return; }


my $x_offset = 0;
my $y_offset = 0;
if ($x > $IMAGE_SIZE && $y > $IMAGE_SIZE) {
#
#Big, scale it down.
#
    if ($x > $y) {
#print STDERR "convert -resize x$IMAGE_SIZE\\> $image tmp.jpg\n";
	system("convert -resize x$IMAGE_SIZE\\> $image tmp.jpg");
	$x_offset = int((int($x * ($IMAGE_SIZE / $y)) - $IMAGE_SIZE) / 2);
    }else{
	system("convert -resize ${IMAGE_SIZE}x\\> $image tmp.jpg");
#print STDERR "convert -resize ${IMAGE_SIZE}x\\> $image tmp.jpg\n";
	$y_offset = int((int($y * ($IMAGE_SIZE / $x)) - $IMAGE_SIZE) / 2);
    }
}else{
    system("mv $image tmp.jpg");

#
#One dimension too big, set crop parameters.
#
    if ($x > $IMAGE_SIZE) {
	$x_offset = int(($IMAGE_SIZE - $x) / 2);
    }else{
	$y_offset = int(($IMAGE_SIZE - $y) / 2);
    }
}


#
#Delete old image, make sure new type is jpg.
#
unlink $image;
$image =~ s/\.(jpg|gif|png|jpeg)$/.jpg/;


#print STDERR "OFF: $x_offset,$y_offset\n";

if ($x_offset || $y_offset) {
    system("convert -crop ${IMAGE_SIZE}x$IMAGE_SIZE+$x_offset+$y_offset tmp.jpg $image"); 
} else {
    system("cp tmp.jpg $image"); 
}

unlink "tmp.jpg";
}


#End



