#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );
use File::Basename;
use PS::IPP::Config 1.01 qw( :standard );

my $joinType = '1and2';
my $in;
my $out;

my ($check, $testdata, $sasdata, $release);

my ($verbose, $save_temps);

GetOptions(
    "testdata=s"        =>  \$testdata,
    "sasdata=s"         =>  \$sasdata,
    "release=s"         =>  \$release,
    "join=s"            =>  \$joinType,
    "check"             =>  \$check,
    "verbose|v"         =>  \$verbose,
    "save-temps"        =>  \$save_temps,
) or pod2usage( 2 );

die "usage: $0 <p2 batch file> [<out>]\n" unless (scalar @ARGV == 2);

$in = shift;
$out = shift;

die "need one of --testdata or --release\n" 
    unless defined $testdata or defined $release or defined $sasdata;


my $jardir = $ENV{JARDIR};
unless ($jardir) {
    $jardir = '/home/panstarrs/bills/jars' unless $jardir;
    print STDERR "JARDIR envrionment variable not found. Using $jardir\n" if $verbose;
    # add it to the enviorment so that the other programs can use it
    $ENV{JARDIR} = $jardir;
}
my $stiltsJar = "$jardir/stilts.jar";
my $stilts = "java -jar $stiltsJar";

my $command;

# find exp_id and exp_name.
$command = "$stilts tcat in=$in'#'FrameMeta icmd='keepcols \"frameID frameName\";' ofmt=ascii | grep -v '#'";
my $line = `$command`;
chomp $line;
my ($exp_id, $exp_name) = split " ", $line;

print "$exp_id $exp_name\n" if $verbose;

# file name for concatenated detection extensions
my $detcat = "cat." . basename($in);

runcommand( "concatp2batch $in $detcat");

if (0) {
$command = "$stilts tcat in=$detcat icmd='head 1;keepcols imageID;' ofmt=ascii | grep -v '#'";
my $imageID = `$command`;
# XXX TODO: check for success
chomp $imageID;
my $exp_id = int($imageID / 100);
print "exp_id is $exp_id\n" if $verbose;
}

my $smf;
if ($testdata) {
#    my $testdata = "/data/ippc19.0/home/bills/ipp/ippToPsps/test/testdata";
    $smf = sprintf "%s/test.%02d.smf", $testdata, $exp_id;
} elsif ($sasdata) {
    # go find the smf for this exposure in the sasdata directory
    my $pattern = "$sasdata/$exp_name*.smf";
    my @smfs = glob($pattern);

    # there should only be one of these
    $smf = $smfs[0];

    die "failed to find smf for $exp_name in sasdata\n" unless $smf;
} else {
    # XXX: look up the smf for the exposure here
    # die "only test mode works right now\n";
    my $cmd = "releasetool -listrelexp -release_name $release -exp_id $exp_id | grep path_base | awk '{print \$3}'";
    print "$cmd\n" if $verbose;
    my $path_base = `$cmd`;
    chomp $path_base;
    die "failed to find path_base for $exp_id\n" unless $path_base;
    $smf = "$path_base.smf";
}
print "$smf for $exp_id is $smf\n" if $verbose;

my $ippcat = "cat." . basename($smf);

$command = "concatsmf $smf $ippcat";
$command .= " --test" if $testdata;
$command .= " --exp_id $exp_id" if $sasdata;

runcommand($command);

my $matched = "m." . basename($out);
runcommand("matchIppToPsps $detcat $ippcat $matched");

if (!$save_temps) {
    unlink $detcat;
    unlink $ippcat;
}

$command = "adddeltacolumns $matched $out";
$command .= " --check" if $check;
$command .= " --save-temps" if $save_temps;

runcommand($command);

exit 0;


sub runcommand {
    my $command = shift;
    print "Running: $command\n" if $verbose;
    my $rc = system $command;
    if ($rc) {
        my $status = $rc >> 8;
        die "$command failed\nrc = $rc status = $status";
    }
}
