#!/usr/bin/perl
# Filename:	gal2album
# Author:	Seth Harbeck <xar (at) armory (dot) com>
# Description:	Converts TheGallery files to album
# I tested it several times on Gallery 1.3.3 and album 2.45
# worked good for me...  make sure to clean the captions.txt:
# vi `find . -name captions.txt`
# -or-  vi */captions.txt

##################################################
# Setup the variables
##################################################
my $PROGNAME = $0;
$PROGNAME =~ s|.*/||;

##################################################
# Usage
##################################################
sub usage {
  foreach my $msg (@_) { print STDERR "ERROR:  $msg\n"; }
  print STDERR "\n";
  print STDERR "Usage:\t$PROGNAME [-d] <file>\n";
  print STDERR "\tConverts TheGallery files to album\n";
  #print STDERR "\t-d\tSet debug mode\n";
  print STDERR "\n";
  exit -1;
}

sub parse_args {
  my ($source,$dest);
  while (my $arg=shift(@ARGV)) {
    if ($arg =~ /^-h$/) { usage(); }
    if ($arg =~ /^-d$/) { $MAIN::DEBUG=1; next; }
    #if ($arg =~ /^-/) { usage("Unknown option: $arg"); }
    usage("Source/destination must be directories") unless -d $arg;
    if ($source) {
      usage("Too many directories specified [$arg, $source, $dest]") if $dest;
      $dest = $arg;
    } else {
      $source = $arg;
    }
  }
  usage("No source defined") unless $source;
  usage("No dest defined") unless $dest;

  ($source,$dest);
}

sub debug {
  return unless $MAIN::DEBUG;
  foreach my $msg (@_) { print STDERR "[$PROGNAME] $msg\n"; }
}

##################################################
# Main code
##################################################
($SOURCE,$DEST) = parse_args();

foreach $dir (`ls $SOURCE`)
{
  if($dir !~ ".dat")
  {
    $newdir = $DEST."/".$dir;
    $olddir = $SOURCE.$dir;
    chomp $newdir;
    chomp $olddir;
    print "Migrating $olddir to $newdir\n";
    `mkdir $newdir`;
    `cp $olddir/\?\?\?.jpg $newdir`;

    #
    #  Generate the caption file
    #
    open (CAPFILE, ">$newdir/captions.txt")|| die "Can't open $newdir caption file $!";
    foreach $x (`sed s/\\{/\\\\n\\{/g $olddir/photos.dat`)
    {
      @broken = split(/:/, $x);
      $Xnum = 0;
      if($broken[2] =~ name && $broken[41] !~ thumb && $broken[41] !~ 7)
      {
        #foreach $xx (@broken)
        #{
        #  #  starting at zero...
        #  #  41 is the caption
        #  #  4 has the prefix with some crap
        #  #  8 is the extension
        #  print $Xnum, $xx, "\n\n";
        #  $Xnum++;
        #  }
        #$prefix,$junk = split(/./, $broken[4]);
      $prefix = $broken[4];
      $prefix =~ s/\"//g;
      $prefix =~ s/.thumb\;s//g;
      $suffix = $broken[8];
      $suffix =~ s/\"//g;
      $suffix =~ s/\;s//g;
      $caption = $broken[41];
      $caption =~ s/\;s//g;
      $caption =~ s/\"//g;

      #    IMG.jpg :: Title :: Description ::
      print CAPFILE $prefix,".",$suffix," :: ",$caption," :: \n";
      }
    }
  }
  close CAPFILE;
}

