#!/usr/bin/env perl

use warnings;
use strict;

## report the program and machine
use Sys::Hostname;
my $host = hostname();
print "\n\n";
print "Starting script $0 on $host\n\n";

use vars qw( $VERSION );
$VERSION = '0.01';

use IPC::Cmd 0.36 qw( can_run run );
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::Stats;
use PS::IPP::Metadata::List qw( parse_md_list );
use Data::Dumper;
use PS::IPP::Config 1.01 qw( :standard );

my $ipprc = PS::IPP::Config->new(); # IPP configuration

use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );

my ($diff_id, $dbname, $outroot, $verbose, $no_update, $no_op);
GetOptions(
    'diff_id|d=s'       => \$diff_id, # Diff identifier
    'dbname|d=s'        => \$dbname, # Database name
    'outroot=s'         => \$outroot, # Output root name
    'verbose'           => \$verbose,   # Print to stdout
    'no-update'         => \$no_update, # Don't update the database?
    'no-op'             => \$no_op, # Don't do any operations?
) or pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage(
    -msg => "Required options: --diff_id --outroot",
    -exitval => 3,
          ) unless defined $diff_id
    and defined $outroot;

my $STATS =
   [
       #          PPSTATS KEYWORD         STATISTIC          DIFFTOOL FLAG
       { name => "ROBUST_MEDIAN",   type => "mean", flag => "-bg",         dtype => "float" },
       { name => "ROBUST_STDEV",    type => "rms",  flag => "-bg_stdev",   dtype => "float" },
       { name => "DT_SUB",          type => "sum",  flag => "-dtime_diff", dtype => "float" },
       { name => "SUBTRACTION.NUM", type => "mean", flag => "-stamps_num", dtype => "int" },
       { name => "SUBTRACTION.RMS", type => "mean", flag => "-stamps_rms", dtype => "float" },
       { name => "NUM_SOURCES",     type => "sum",  flag => "-sources",    dtype => "int" },
       { name => "GOOD_PIXEL_FRAC", type => "mean", flag => "-good_frac",  dtype => "float" },
   ];
my $stats = PS::IPP::Metadata::Stats->new($STATS); # Stats parser

# Look for programs we need
my $missing_tools;
my $difftool = can_run('difftool') or (warn "Can't find difftool" and $missing_tools = 1);
my $ppSub = can_run('ppSub') or (warn "Can't find ppSub" and $missing_tools = 1);
if ($missing_tools) {
    warn("Can't find required tools.");
    exit($PS_EXIT_CONFIG_ERROR);
}

# Get list of components for subtraction
my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
my $files;
{
    my $command = "$difftool -inputskyfile -diff_id $diff_id";
    $command .= " -dbname $dbname" if defined $dbname;
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    unless ($success) {
        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
        &my_die("Unable to perform difftool -inputskyfile: $error_code", $diff_id, $error_code);
    }

    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
        &my_die("Unable to parse metadata config doc", $diff_id, $PS_EXIT_PROG_ERROR);
    $files = parse_md_list($metadata) or
        &my_die("Unable to parse metadata list", $diff_id, $PS_EXIT_PROG_ERROR);
}

&my_die("Subtraction list does not contain exactly two elements", $diff_id, $PS_EXIT_SYS_ERROR) unless
    scalar @$files == 2;

# Identify the input and the template
my ($input, $inputMask, $inputWeight, $inputPath); # Input files and path
my ($template, $templateMask, $templateWeight, $templatePath, $templateSources); # Template files and path
my $tess_id;                    # Tesselation identifier
my $skycell_id;                 # Skycell identifier
my $camera;                     # Camera
foreach my $file (@$files) {
    if (defined $file->{template} and $file->{template}) {
        $template = $file->{uri};
        $templatePath = $file->{path_base};
        if ($file->{warp_id} == 0) {
            $templateMask = "PPSTACK.OUTPUT.MASK";
            $templateWeight = "PPSTACK.OUTPUT.WEIGHT";
            $templateSources = "PSPHOT.OUTPUT";
        } else {
            $templateMask = "PSWARP.OUTPUT.MASK";
            $templateWeight = "PSWARP.OUTPUT.WEIGHT";
            $templateSources = "PSWARP.OUTPUT.SOURCES";
        }
    } else {
        $input = $file->{uri};
        $inputPath = $file->{path_base};
        if ($file->{warp_id} == 0) {
            $inputMask = "PPSTACK.OUTPUT.MASK";
            $inputWeight = "PPSTACK.OUTPUT.WEIGHT";
        } else {
            $inputMask = "PSWARP.OUTPUT.MASK";
            $inputWeight = "PSWARP.OUTPUT.WEIGHT";
        }
    }
    if (defined $tess_id) {
        &my_die("Tesselation identifiers don't match", $diff_id, $PS_EXIT_SYS_ERROR) unless
            $file->{tess_id} eq $tess_id;
    } else {
        $tess_id = $file->{tess_id};
    }
    if (defined $skycell_id) {
        &my_die("Skycell identifiers don't match", $diff_id, $PS_EXIT_SYS_ERROR) unless
            $file->{skycell_id} eq $skycell_id;
    } else {
        $skycell_id = $file->{skycell_id};
    }
    if (defined $camera) {
        &my_die("Cameras don't match", $diff_id, $PS_EXIT_SYS_ERROR) unless $file->{camera} eq $camera;
    } else {
        $camera = $file->{camera};
    }

}

&my_die("Unable to identify template", $diff_id, $PS_EXIT_SYS_ERROR) unless defined $template;
&my_die("Unable to identify input", $diff_id, $PS_EXIT_SYS_ERROR) unless defined $input;
&my_die("Unable to identify camera", $diff_id, $PS_EXIT_SYS_ERROR) unless defined $camera;
$ipprc->define_camera($camera);

$templateMask = $ipprc->filename($templateMask, $templatePath);
$inputMask = $ipprc->filename($inputMask, $inputPath);
$templateWeight = $ipprc->filename($templateWeight, $templatePath);
$inputWeight = $ipprc->filename($inputWeight, $inputPath);
$templateSources = $ipprc->filename($templateSources, $templatePath);

&my_die("Couldn't find input: $template", $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($template);
&my_die("Couldn't find input: $templateMask", $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($templateMask);
&my_die("Couldn't find input: $templateWeight", $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($templateWeight);
&my_die("Couldn't find input: $input", $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($input);
&my_die("Couldn't find input: $inputMask", $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($inputMask);
&my_die("Couldn't find input: $inputWeight", $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($inputWeight);
&my_die("Couldn't find input: $templateSources", $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($templateSources);

# Get the output filenames
my $outputName = $ipprc->filename("PPSUB.OUTPUT", $outroot);
my $outputMask = $ipprc->filename("PPSUB.OUTPUT.MASK", $outroot);
my $outputWeight = $ipprc->filename("PPSUB.OUTPUT.WEIGHT", $outroot);
my $outputSources = $ipprc->filename("PSPHOT.OUTPUT", $outroot);
#my $bin1Name =  $ipprc->filename("PPSUB.BIN1", $outroot);
#my $bin2Name =  $ipprc->filename("PPSUB.BIN2", $outroot);
my $outputStats = $ipprc->filename("SKYCELL.STATS", $outroot);
my $traceDest = $ipprc->filename("TRACE.EXP", $outroot);
my $logDest = $ipprc->filename("LOG.EXP", $outroot);

# Perform subtraction
unless ($no_op) {
    my $command = "$ppSub $input $template $outroot";
    $command .= " -inmask $inputMask";
    $command .= " -refmask $templateMask";
    $command .= " -inweight $inputWeight";
    $command .= " -refweight $templateWeight";
    $command .= " -stats $outputStats";
    $command .= " -recipe PPSTATS WARPSTATS";
    $command .= " -sources $templateSources";
    $command .= " -photometry";
    $command .= " -tracedest $traceDest -log $logDest";
    $command .= " -dbname $dbname" if defined $dbname;

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    unless ($success) {
        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
        &my_die("Unable to perform ppSub: $error_code", $diff_id, $error_code);
    }
    &my_die("Couldn't find expected output file: $outputName", $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputName);
    &my_die("Couldn't find expected output file: $outputMask", $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputMask);
    &my_die("Couldn't find expected output file: $outputWeight", $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputWeight);
    &my_die("Couldn't find expected output file: $outputSources", $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputSources);
#    &my_die("Couldn't find expected output file: $bin1Name",    $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($bin1Name);
#    &my_die("Couldn't find expected output file: $bin2Name",    $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($bin2Name);
    &my_die("Couldn't find expected output file: $outputStats", $diff_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputStats);

    # Get the statistics on the residual image
    my $statsFile;              # File handle
    open $statsFile, $ipprc->file_resolve($outputStats) or &my_die("Can't open statistics file $outputStats: $!", $diff_id, $PS_EXIT_SYS_ERROR);
    my @contents = <$statsFile>; # Contents of file
    close $statsFile;
    my $metadata = $mdcParser->parse(join "", @contents) or
        &my_die("Unable to parse metadata config doc", $diff_id, $PS_EXIT_PROG_ERROR);
    $stats->parse($metadata) or &my_die("Unable to find all values in statistics output.", $diff_id, $PS_EXIT_PROG_ERROR);
}

unless ($no_update) {

    # Add the subtraction result
    {
        my $command = "$difftool -adddiffskyfile -diff_id $diff_id -uri $outputName -path_base $outroot";
        $command .= $stats->cmdflags();
        $command .= " -hostname $host" if defined $host;
        $command .= " -dbname $dbname" if defined $dbname;

        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
            run(command => $command, verbose => $verbose);
        unless ($success) {
            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
            &my_die("Unable to perform difftool -adddiffskyfile: $error_code", $diff_id, $error_code);
        }
    }

    # Register the run as completed
    {
        my $command = "$difftool -updaterun -diff_id $diff_id -state stop"; # Command to run difftool
        $command .= " -dbname $dbname" if defined $dbname;

        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
            run(command => $command, verbose => $verbose);
        unless ($success) {
            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
            warn("Unable to perform difftool -updaterun: $error_code\n");
            exit($error_code);
        }
    }
}


sub my_die
{
    my $msg = shift;            # Warning message on die
    my $diff_id = shift;        # Diff identifier
    my $exit_code = shift;      # Exit code to add

    warn($msg);
    if (defined $diff_id and not $no_update) {
        my $command = "$difftool -adddiffskyfile -diff_id $diff_id -code $exit_code";
        $command .= " -hostname $host" if defined $host;
        $command .= " -dbname $dbname" if defined $dbname;
        run(command => $command, verbose => $verbose);
    }
    exit $exit_code;
}

END {
    my $exit = $?;
    system("sync") == 0 or die "failed to execute sync: $!";
    $? = $exit;
}

__END__
