#!/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 DateTime;
my $mjd_start = DateTime->now->mjd;   # MJD of starting script

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::List qw( parse_md_list );
use Data::Dumper;
use PS::IPP::Config 1.01 qw( :standard );

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

# 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);
my $ppStatsFromMetadata = can_run('ppStatsFromMetadata') or (warn "Can't find ppStatsFromMetadata" and $missing_tools = 1);
if ($missing_tools) {
    warn("Can't find required tools.");
    exit($PS_EXIT_CONFIG_ERROR);
}

my ($diff_id, $dbname, $threads, $outroot, $reduction, $inverse, $verbose, $no_update, $no_op, $redirect);
my ($skycell_id, $diff_skyfile_id);
GetOptions(
    'diff_id=s'         => \$diff_id, # Diff identifier
    'skycell_id=s'      => \$skycell_id, # Skycell identifier
    'diff_skyfile_id=s' => \$diff_skyfile_id, # Diff identifier
    'dbname|d=s'        => \$dbname, # Database name
    'threads=s'         => \$threads,   # Number of threads to use
    'outroot=s'         => \$outroot, # Output root name
    'inverse'           => \$inverse, # Make inverse subtraction?
    'reduction=s'       => \$reduction, # Reduction class
    'verbose'           => \$verbose,   # Print to stdout
    'no-update'         => \$no_update, # Don't update the database?
    'no-op'             => \$no_op, # Don't do any operations?
    'redirect-output'   => \$redirect,
) or pod2usage( 2 );

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

my $ipprc = PS::IPP::Config->new() or my_die( "Unable to set up", $diff_id, $skycell_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration

# XXX camera is not known here; cannot use filerules...
# my $logDest = $ipprc->filename("LOG.EXP", $outroot);
my $logDest = "$outroot.log";
$ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR ) if $redirect;

my $source_id = $ipprc->source_id($dbname, $PS_TABLE_ID_DIFF);

# 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 -skycell_id $skycell_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, $skycell_id, $error_code);
    }

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

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

# Identify the input and the template
my ($input, $inputMask, $inputVariance, $inputPath, $inputSources); # Input files and path
my ($template, $templateMask, $templateVariance, $templatePath, $templateSources); # Template files and path
my $tess_id;                    # Tesselation identifier
my $camera;                     # Camera
my ($inputMagic, $templateMagic); # Are the inputs been magicked?
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";
            $templateVariance = "PPSTACK.OUTPUT.VARIANCE";
            $templateSources = "PSPHOT.OUT.CMF.MEF";  ## this must be consistent with the value in stack_skycell.pl:161
            # template is a stack so it doesn't need to be magicked
            $templateMagic = 1;
            ## use an explicit stack name for psphot output objects
        } else {
            $templateMask = "PSWARP.OUTPUT.MASK";
            $templateVariance = "PSWARP.OUTPUT.VARIANCE";
            $templateSources = "PSWARP.OUTPUT.SOURCES";
            $templateMagic = $file->{magicked};
        }
    } else {
        $input = $file->{uri};
        $inputPath = $file->{path_base};
        $inputMagic = $file->{magicked};    # if input is a stack the output can't be "magicked"
        if ($file->{warp_id} == 0) {
            $inputMask = "PPSTACK.OUTPUT.MASK";
            $inputVariance = "PPSTACK.OUTPUT.VARIANCE";
            $inputSources = "PSPHOT.OUT.CMF.MEF";  ## this must be consistent with the value in stack_skycell.pl:161
        } else {
            $inputMask = "PSWARP.OUTPUT.MASK";
            $inputVariance = "PSWARP.OUTPUT.VARIANCE";
            $inputSources = "PSWARP.OUTPUT.SOURCES";
        }
    }
    if (defined $tess_id) {
        &my_die("Tesselation identifiers don't match", $diff_id, $skycell_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, $skycell_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, $skycell_id, $PS_EXIT_SYS_ERROR) unless $file->{camera} eq $camera;
    } else {
        $camera = $file->{camera};
    }
}

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

# Compute the magicked status of the output.
# The output file will be considered magicked if the input has been magicked and the
# template is either a stack or a warp that has been magicked.
# note that difftool -inputskyfile outputs the magicked boolean as an int not T or F
# because the output is constructed from a union of two selects
my $magicked = $inputMagic && $templateMagic;

# Recipes to use based on reduction class
$reduction = 'DEFAULT' unless defined $reduction;
my $recipe_ppSub = $ipprc->reduction($reduction, 'DIFF_PPSUB'); # Recipe to use for ppSub
my $recipe_psphot  = $ipprc->reduction($reduction, 'DIFF_PSPHOT'); # Recipe to use for psphot
unless ($recipe_ppSub and $recipe_psphot) {
    &my_die("Couldn't find selected reduction for DIFF_PPSUB and DIFF_PSPHOT: $reduction\n", $diff_id, $skycell_id, $PS_EXIT_CONFIG_ERROR);
}

# print "templateMask: $templateMask\n";
# print "templatePath: $templatePath\n";
# print "inputMask: $inputMask\n";
# print "inputPath: $inputPath\n";
# print "templateVariance: $templateVariance\n";
# print "inputVariance: $inputVariance\n";
# print "templateSources: $templateSources\n";
# print "inputSources: $inputSources\n";

$inputMask = $ipprc->filename($inputMask, $inputPath);
$inputVariance = $ipprc->filename($inputVariance, $inputPath);
$inputSources = $ipprc->filename($inputSources, $inputPath);

$templateMask = $ipprc->filename($templateMask, $templatePath);
$templateVariance = $ipprc->filename($templateVariance, $templatePath);
$templateSources = $ipprc->filename($templateSources, $templatePath);

print "templateMask: $templateMask\n";
print "templatePath: $templatePath\n";
print "inputMask: $inputMask\n";
print "inputPath: $inputPath\n";
print "templateVariance: $templateVariance\n";
print "inputVariance: $inputVariance\n";
print "templateSources: $templateSources\n";
print "inputSources: $inputSources\n";

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

# Get the output filenames
my $outputName = $ipprc->filename("PPSUB.OUTPUT", $outroot);
my $outputMask = $ipprc->filename("PPSUB.OUTPUT.MASK", $outroot);
my $outputVariance = $ipprc->filename("PPSUB.OUTPUT.VARIANCE", $outroot);
my $outputSources = $ipprc->filename("PPSUB.OUTPUT.SOURCES", $outroot);
my $jpeg1Name = $ipprc->filename("PPSUB.OUTPUT.JPEG1", $outroot);
my $jpeg2Name = $ipprc->filename("PPSUB.OUTPUT.JPEG2", $outroot);
my $configuration = $ipprc->filename("PPSUB.CONFIG", $outroot);
my $outputStats = $ipprc->filename("SKYCELL.STATS", $outroot);
my $traceDest = $ipprc->filename("TRACE.EXP", $outroot);

my ($inverseName, $inverseMask, $inverseVariance, $inverseSources);
if ($inverse) {
    $inverseName = $ipprc->filename("PPSUB.INVERSE", $outroot);
    $inverseMask = $ipprc->filename("PPSUB.INVERSE.MASK", $outroot);
    $inverseVariance = $ipprc->filename("PPSUB.INVERSE.VARIANCE", $outroot);
    $inverseSources = $ipprc->filename("PPSUB.INVERSE.SOURCES", $outroot);
}

my $cmdflags;

# Perform subtraction
unless ($no_op) {
    my $command = "$ppSub $outroot";
    $command .= " -inimage $input";
    $command .= " -refimage $template";
    $command .= " -inmask $inputMask";
    $command .= " -refmask $templateMask";
    $command .= " -invariance $inputVariance";
    $command .= " -refvariance $templateVariance";
    $command .= " -insources $inputSources";
    $command .= " -refsources $templateSources";
    $command .= " -stats $outputStats";
    $command .= " -threads $threads" if defined $threads;
    $command .= " -recipe PPSUB $recipe_ppSub";
    $command .= " -recipe PSPHOT $recipe_psphot";
    $command .= " -recipe PPSTATS WARPSTATS";
    $command .= " -F PSPHOT.PSF.SAVE PSPHOT.PSF.SKY.SAVE";
    $command .= " -F PSPHOT.OUTPUT PSPHOT.OUT.CMF.MEF";
    $command .= " -F PSPHOT.BACKMDL PSPHOT.BACKMDL.MEF";
    $command .= " -photometry";
    $command .= " -inverse" if $inverse;
    $command .= " -tracedest $traceDest -log $logDest";
    $command .= " -dumpconfig $configuration";
    $command .= " -dbname $dbname" if defined $dbname;
    $command .= " -image_id $diff_skyfile_id" if defined $diff_skyfile_id;
    $command .= " -source_id $source_id" if defined $source_id;

    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, $skycell_id, $error_code);
    }

    my $outputStatsReal = $ipprc->file_resolve($outputStats);
    &my_die("Couldn't find expected output file: $outputStats", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless -f $outputStatsReal;

    # measure chip stats
    $command = "$ppStatsFromMetadata $outputStatsReal - DIFF_SKYCELL";
    ( $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 ppStatsFromMetadata: $error_code", $diff_id, $skycell_id, $error_code);
    }
    foreach my $line (@$stdout_buf) {
        $cmdflags .= " $line";
    }
    chomp $cmdflags;

    my ($quality) = $cmdflags =~ /-quality (\d+)/; # Quality flag

    if (!$quality) {
        &my_die("Couldn't find expected output file: $outputName", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputName);
        &my_die("Couldn't find expected output file: $outputMask", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputMask);
        &my_die("Couldn't find expected output file: $outputVariance", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputVariance);
        &my_die("Couldn't find expected output file: $outputSources", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputSources);
        &my_die("Couldn't find expected output file: $jpeg1Name",    $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($jpeg1Name);
        &my_die("Couldn't find expected output file: $jpeg2Name",    $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($jpeg2Name);
        if ($inverse) {
            &my_die("Couldn't find expected output file: $inverseName", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($inverseName);
            &my_die("Couldn't find expected output file: $inverseMask", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($inverseMask);
            &my_die("Couldn't find expected output file: $inverseVariance", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($inverseVariance);
            &my_die("Couldn't find expected output file: $inverseSources", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($inverseSources);
        }
    }
}

unless ($no_update) {

    # Add the subtraction result
    {
        my $command = "$difftool -adddiffskyfile -diff_id $diff_id -skycell_id $skycell_id -path_base $outroot";
        $command .= " $cmdflags";
        $command .= " -magicked" if $magicked;
        $command .= (" -dtime_script " . ((DateTime->now->mjd - $mjd_start) * 86400));
        $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, $skycell_id, $error_code);
        }
    }
}


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

    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;

    warn($msg);
    if (defined $diff_id and defined $skycell_id and not $no_update) {
        my $command = "$difftool -adddiffskyfile -diff_id $diff_id -skycell_id $skycell_id -fault $exit_code";
        $command .= (" -dtime_script " . ((DateTime->now->mjd - $mjd_start) * 86400));
        $command .= " -hostname $host" if defined $host;
        $command .= " -path_base $outroot" if defined $outroot;
        $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__
