#!/usr/bin/perl -w

#---libsetup---

# having . in @INC can cause tainting issues for use

no lib '.';

use FindBin;
BEGIN {
  ($dir)=($FindBin::Bin=~/^([\w\d\-\/\.]+)$/)
    or die "invalid current directory $FindBin::Bin";
}
use lib $dir;

#---endlibsetup---

use PhotoPub::Global qw(&init &finit);
use PhotoPub::CLBase qw();
use PhotoPub::Config;

use PhotoPub::Handlers qw(&forallhandlers &listhandlephoto &handlephoto 
			  &counthandlers &parameterhandlephoto);
use PhotoPub::Images qw(&picrange);

my $command=shift @ARGV;

if($command eq 'interactive') {
  $command=shift @ARGV;
  while(<>) {
    &init();
    chomp;
    &onearg($_);
    &finit();
  }
} else {
  &init();
  foreach my $arg (@ARGV) {
    &onearg($arg);
  }
  &finit();
}

sub onearg {
  my ($arg)=@_;
  if($command eq 'enumsubpaths') {
    print "$arg\n";
    chop($arg) if substr($arg,-1) eq '/';
    &forallhandlers('enumsubpaths',$arg,sub {
		      my ($thispath,$subpaths)=@_;
		      print "-$thispath\n";
		      foreach my $thissubpath (@$subpaths) {
			print "--$thissubpath\n";
		      }
		    });
  } elsif($command eq 'cachedir') {
    print "$arg ";
    chop($arg) if substr($arg,-1) eq '/';
    my $prefix=&handlephoto('cachefileprefix',$arg);
    if (defined $prefix) {
      print "$prefix";
    } else {
      print "undefined";
    }
    print "\n";
  } elsif($command eq 'album') {
    my $album=$arg;
    print "$album\n\n";
    chop($album) if substr($album,-1) eq '/';
    my $items=&listhandlephoto('album',$album);
    foreach my $item (@$items) {
      if($item->{'type'} eq 'group') {
	print 'range: '.$item->{'range'}.' : '.$item->{'description'}."\n";
      } else {
	print 'album: '.$item->{'album'}.' : '.$item->{'title'}."\n";
      }
    }
  } elsif($command eq 'range') {
    print "$arg\n\n";
    my @items=&picrange($arg);
    foreach my $item (@items) {
      print "$item\n";
    }
  } elsif($command eq 'rangetitle') {
    my ($album,$range)=split /\s+/,$arg;
    print "$album $range\n";
    my $info=&parameterhandlephoto('rangeinfo',$album,$range);
    print "Title: ".$info->{'description'}."\n" if defined $info;
  } elsif($command eq 'checkconfig') {
    print "Checking $arg\n";
    chop($arg) if substr($arg,-1) eq '/';
    &handlephoto('test',$arg);
    print &counthandlers()." handlers loaded\n";
  } elsif($command eq 'whentaken') {
    my $whentaken=&handlephoto('whentaken',$arg);
    $whentaken = 'undefined' unless defined $whentaken;
    print "$arg: $whentaken\n";
  } elsif($command eq 'options') {
    my $options=&handlephoto('options',$arg);
    while (my ($key,$val) = each %$options) {
       print "$key: $val\n";
    }
  }
}
