#!/usr/bin/perl
# Filename:	in_album
# Author:	David Ljung Madison <DaveSource.com>
# See License:	http://MarginalHacks.com/License
# Description:	Takes in new images, breaks them up into new directories
#		and runs album
use strict;

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

my $INCOMING_DIR	= ".";			# Incoming directory for imgs
my $ALBUM_DIRS		= "images_%0.2d";	# Where they go (sprintf)
my $ALBUM		= "album";		# The album program
my $ALBUM_ARGS		= "";			# Options (-theme ..., etc..)
my $IMAGES_PER_DIR	= 50;			# Images per image directory

##################################################
# Main code
##################################################
sub dir_contents {
  my ($dir) = @_;
  opendir(IN,$dir);
  my @in = grep(!/^\.{1,2}$/, readdir(IN));
  closedir IN;
  @in;
}

# This is wasteful, we could start at the end, but heck...
sub next_album_dir {
  my $c = 1;
  while (1) {
    my $d = sprintf($ALBUM_DIRS,$c++);
    unless (-d $d) {
      mkdir $d, 0755 || die("Couldn't mkdir [$d]\n");
      return $d;
    }
    my $num = dir_contents($d);
    return $d if $num < $IMAGES_PER_DIR;
  }
}

sub album {
  my ($d,@extra) = @_;
  print "$ALBUM $ALBUM_ARGS @extra $d\n";
  system("$ALBUM $ALBUM_ARGS @extra $d");
}

# Safe move, don't overwrite
sub move {
  my ($from,$to,$name) = @_;

  my ($startname,$c) = ($name,2);
  while (-f "$to/$name") { $name = $startname . "." . $c++; }
  rename "$from/$startname", "$to/$name" ||
    die("Couldn't move: $from/$startname -> $to/$name\n");
}

sub main {
  my @in = dir_contents($INCOMING_DIR);

  my @build_dirs;

  while (@in) {
    my $d = next_album_dir;
    my $space = $IMAGES_PER_DIR - dir_contents($d);
    my @move = splice(@in,0,$space);
    map { move($INCOMING_DIR,$d,$_); } @move;
    push(@build_dirs,$d);
  }

  # Run album, only on directories needed
  album(".","-depth 1");
  map { album($_); } @build_dirs;
}
main();
