#!/usr/bin/env perl
#
# Execute a get_image job for the postage stamp server
#

use strict;
use warnings;

use Getopt::Long qw( GetOptions );
use Pod::Usage qw( pod2usage );
use DBI;
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::Stats;
use PS::IPP::Metadata::List qw( parse_md_list );
use File::Copy;
use File::Basename;

use PS::IPP::Config qw($PS_EXIT_SUCCESS
		       $PS_EXIT_UNKNOWN_ERROR
		       $PS_EXIT_SYS_ERROR
		       $PS_EXIT_CONFIG_ERROR
		       $PS_EXIT_PROG_ERROR
		       $PS_EXIT_DATA_ERROR
		       $PS_EXIT_TIMEOUT_ERROR
		       metadataLookupStr
		       metadataLookupBool
		       caturi
		       );
my $product;
my $fileset;

my $uri;
my $out_dir;

my $verbose = 1;
my $ipprc;

#
# parse args
#

GetOptions(
        'uri=s'           =>      \$uri,
        'out_dir=s'       =>      \$out_dir,
) or pod2usage(2);

my $err = "";

if (!$uri) {
    die("--uri is required to specify the file list");
}
if (!$out_dir) {
    die("--out_dir is required to specify the output fileset");
}

# collapse any multiple slashes in output_dir
$out_dir = File::Spec->canonpath($out_dir);

my @path = split(/\//, $out_dir);

my $nelem = @path;
if ($nelem < 2) {
    die("$out_dir is not a valid output fileset directory");
}
$fileset = $path[$nelem-1];
$product = $path[$nelem-2];

$_ = $out_dir;
my ($ds_dir) = m%(.*)/$product/$fileset%;

if ($verbose) {
    print STDERR "DS root:  $ds_dir\n";
    print STDERR "Product:  $product\n";
    print STDERR "Fileset:  $fileset\n";
    print STDERR "Filelist: $uri\n";
}


if (!stat("$ds_dir/index.txt")) {
    $err .= "Data Store not found at '$ds_dir'.\n"
}

show_usage("Invalid product '$product'.")
    unless defined stat("$ds_dir/$product/index.txt");

if (! open(INPUT, "<$uri") ) {
    die("failed to open file list: $uri");
}

my $reglist = "$out_dir/reglist";
if (! open(REGLIST, ">$reglist") ) {
    die("failed to open registration list: $reglist");
}

my @files;
while (<INPUT>) {
    chomp;
    my @fields = split /\|/;
    my $pathname = shift @fields;

    #my ($volume, $directories, $filename) = File::Spec->splitpath($pathname);

    ($pathname , my $filename) = resolvepath($pathname);

    if ($verbose) {
        print STDERR "$pathname @fields\n";
    }

    if (! symlink $pathname, "$out_dir/$filename" ) {
        die("failed trying to create symlink to $pathname in $out_dir");
    }

    print REGLIST "$filename|";
    foreach my $f (@fields) {
        print REGLIST "$f|";
    }
    print REGLIST "\n";
}

close(REGLIST);

#only thing left to do is register the fileset
exec "dsreg < $reglist --add --product $product --fileset $fileset --type PSRESULTS";


sub resolvepath {
    my $pathname = $_[0];

    my $slash = index($pathname, "/");
    if ($slash != 0) {
        if (!$ipprc) {
            $ipprc = PS::IPP::Config->new();
        }
        $pathname = $ipprc->convert_filename_absolute($pathname);
    }

    my $file = basename($pathname);

    return ($pathname, $file);
}
