#!/usr/bin/perl

###############################################
# Copyright 2007 Jeremy Mooney
# http://jeremy.qux.net/projects/sm-fileupload/
# Last Modified 2007-07-31
###############################################

use strict;

unless ($ARGV[0]) {
   die "Usage: iphoto-uploadalbum.pl <htmlpagesdir> <albumid> <email> <passwd>\n";
}

my $albumid = $ARGV[1];
unless ($albumid =~ m/^\d+$/) {
   die "Invalid Album ID";
}
unless($ARGV[2] =~ m/@/) {
   die "Invalid email address";
}
my $session = qx!sm-fileupload.pl --getsession --email $ARGV[2] --passwd $ARGV[3]!;
unless ($session =~ m/^\w+$/) {
   die "Could not acquire valid session ID\n$session\n";
}

opendir(DIRHANDLE,$ARGV[0]) || die;
my $direntry;
while ($direntry = readdir DIRHANDLE) {
   next unless ($direntry =~ m/\.html$/);
   open(FILE,$direntry) || die "Could not open file $direntry\n";
   my $filedata;
   while(<FILE>) {
      $filedata .= $_;
   }
   close(FILE);
   my ($caption,$filename,$filepath);
   $filedata =~ s/<br><br>.*<br><br>//; # Remove the top line
   if ($filedata =~ m/<br><br>([^<]*)</s) {
      $caption = $1;
      chomp($caption);
      $caption =~ s/"//g;
   }
   if ($filedata =~ m/ src="([^"]+)"/) {
      $filepath = $1;
      if ($filepath=~ m/([^\/]+)$/) {
         $filename = $1;
      }
   }
   unless($filepath) {
      print "Could not parse image file data from $direntry!\n";
      next;
   }
   print "Uploading $filename ($caption)...\n";
   my $path = "sm-fileupload.pl --sessionid $session --albumid $albumid --file \"$filepath\"";
   $path .= " --filename \"$filename\"" if ($filename);
   $path .= " --caption \"$caption\"" if ($caption);
   print qx!$path!;
   print "\n";
}

print qx!sm-fileupload.pl --logout --sessionid $session!;
