#!/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 File::Spec;
use File::Temp qw( tempfile );
use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::Stats;
use PS::IPP::Metadata::List qw( parse_md_list );
use PS::IPP::Config 1.01 qw( :standard );

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

my ($warp_id, $skycell_id, $tess_dir, $camera, $dbname, $outroot, $verbose, $no_update, $no_op, $redirect, $save_temps);
GetOptions(
    'warp_id|i=s'       => \$warp_id, # Warp identifier
    'skycell_id|s=s'    => \$skycell_id, # Skycell identifier
    'tess_dir|s=s'       => \$tess_dir, # Tesselation identifier
    'camera|c=s'        => \$camera, # Camera name
    '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?
    'redirect-output'   => \$redirect,
    'save-temps'        => \$save_temps, # Save temporary files?
) or pod2usage( 2 );

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

$ipprc->define_camera($camera);

my $logDest = $ipprc->filename("TRACE.EXP", $outroot, $skycell_id);

$ipprc->redirect_output($logDest) if $redirect;

my $STATS =
   [
       #          PPSTATS KEYWORD         STATISTIC          WARPTOOL FLAG
       { name => "ROBUST_MEDIAN",   type => "mean", flag => "-bg",         dtype => "float" },
       { name => "ROBUST_STDEV",    type => "rms",  flag => "-bg_stdev",   dtype => "float" },
       { name => "DT_WARP",         type => "sum",  flag => "-dtime_warp", dtype => "float" },
       { name => "GOOD_PIXEL_FRAC", type => "mean", flag => "-good_frac",  dtype => "float" },
       { name => "RANGE.XMIN",      type => "mean", flag => "-xmin",       dtype => "int"   },
       { name => "RANGE.XMAX",      type => "mean", flag => "-xmax",       dtype => "int"   },
       { name => "RANGE.YMIN",      type => "mean", flag => "-ymin",       dtype => "int"   },
       { name => "RANGE.YMAX",      type => "mean", flag => "-ymax",       dtype => "int"   },
   ];
my $stats = PS::IPP::Metadata::Stats->new($STATS); # Stats parser

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

# Get list of component imfiles for exposure
my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
my $imfiles;
{
    # XXX change -tess_id to -tess_dir when db schema is updated
    my $command = "$warptool -scmap -warp_id $warp_id -skycell_id $skycell_id -tess_id $tess_dir";
    $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 warptool -scmap: $error_code", $warp_id, $skycell_id, $tess_dir, $error_code);
    }

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

# Where do we get the astrometry source from?
my $astromSource;               # The astrometry source
{
    my $command = "$ppConfigDump -camera $camera -dump-recipe PSWARP -";
    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 ppConfigDump: $error_code", $warp_id, $error_code);
    }
    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
        &my_die("Unable to parse metadata config doc", $warp_id, $PS_EXIT_PROG_ERROR);
    $astromSource = metadataLookupStr($metadata, 'ASTROM.SOURCE');
}

my $outputImage = $ipprc->filename("PSWARP.OUTPUT", $outroot, $skycell_id );
my $outputMask = $ipprc->filename("PSWARP.OUTPUT.MASK", $outroot, $skycell_id);
my $outputWeight = $ipprc->filename("PSWARP.OUTPUT.WEIGHT", $outroot, $skycell_id);
my $outputSources = $ipprc->filename("PSWARP.OUTPUT.SOURCES", $outroot, $skycell_id);
my $outputPSF = $ipprc->filename("PSPHOT.PSF.SAVE", $outroot, $skycell_id);
my $outputBin1 = $ipprc->filename("PSWARP.BIN1", $outroot, $skycell_id );
my $outputBin2 = $ipprc->filename("PSWARP.BIN2", $outroot, $skycell_id );
my $outputStats = $ipprc->filename("SKYCELL.STATS", $outroot, $skycell_id );
my $traceDest = $ipprc->filename("TRACE.EXP", $outroot, $skycell_id);

my $skyFile = $ipprc->filename("SKYCELL.TEMPLATE", $outroot, $skycell_id );
$ipprc->skycell_file( $tess_dir, $skycell_id, $skyFile, $verbose ) or &my_die("Unable to generate template skycell", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR);

# Get list of filenames
my $outrootResolved = $ipprc->file_resolve( $outroot );
my ($imageFile,  $imageName)  = tempfile( "$outrootResolved.image.list.XXXX",  UNLINK => !$save_temps);
my ($maskFile,   $maskName)   = tempfile( "$outrootResolved.mask.list.XXXX",   UNLINK => !$save_temps);
my ($weightFile, $weightName) = tempfile( "$outrootResolved.weight.list.XXXX", UNLINK => !$save_temps);
my ($astromFile, $astromName) = tempfile( "$outrootResolved.astrom.list.XXXX", UNLINK => !$save_temps);

my $wrote_astrom = 0;
foreach my $imfile (@$imfiles) {
    my $image = $imfile->{uri}; # Image name
    my $mask = $ipprc->filename("PPIMAGE.CHIP.MASK", $imfile->{chip_path_base}, $imfile->{class_id}); # Mask name
    my $weight = $ipprc->filename("PPIMAGE.CHIP.WEIGHT", $imfile->{chip_path_base}, $imfile->{class_id}); # Mask name

    &my_die("Couldn't find input file: $image", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($image);
    &my_die("Couldn't find input file: $mask", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($mask);

    my $astrom;         # Astrometry file
    if ($astromSource eq 'PSASTRO.OUTPUT.MEF') {
        $astrom = $ipprc->filename($astromSource, $imfile->{cam_path_base});
    } elsif ($astromSource eq 'PSASTRO.OUTPUT') {
        my $chipRoot = $imfile->{chip_path_base};
        my $classID = $imfile->{class_id};
        $astrom = $ipprc->filename($astromSource, $chipRoot, $classID); # Astrometry file
    }

    &my_die("Couldn't find input file: $astrom", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless defined $astrom and $ipprc->file_exists($astrom);

    print $imageFile  "$image\n";
    print $maskFile   "$mask\n";
    print $weightFile "$weight\n";

    if (!$wrote_astrom) {
        print $astromFile "$astrom\n";
        # XXX simplify this?  only ever have one file for astrometry (must be MEF)
        if ($astromSource eq 'PSASTRO.OUTPUT.MEF') {
            $wrote_astrom = 1;
        }
    }
}
close $imageFile;
close $maskFile;
close $weightFile;
close $astromFile;


# Run pswarp
my $accept = 1;                 # Accept the skycell?
unless ($no_op) {
    my $command = "$pswarp";
    $command .= " -list $imageName";
    $command .= " -masklist $maskName";
    $command .= " -weightlist $weightName";
    $command .= " -astromlist $astromName";
    $command .= " $outroot $skyFile";
    $command .= " -stats $outputStats";
    $command .= " -recipe PPSTATS WARPSTATS";
    $command .= " -psf";        # Turn on PSF determination
    $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 pswarp: $error_code", $warp_id, $skycell_id, $tess_dir, $error_code);
    }

    # Check first for the stats file, and if the ACCEPT flag is set.
    &my_die("Couldn't find expected output file: $outputStats", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputStats);
    # Get the statistics on the warped image
    my $statsFile;              # File handle
    open $statsFile, $ipprc->file_resolve($outputStats) or die "Can't open statistics file $outputStats: $!\n";
    my @contents = <$statsFile>; # Contents of file
    close $statsFile;
    my $contents = join "", @contents;

    my $metadata = $mdcParser->parse($contents)
        or &my_die("Unable to parse metadata config", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_PROG_ERROR);
    $accept = metadataLookupBool($metadata, "ACCEPT");
    if ($accept) {
        $stats->parse($metadata) or &my_die("Unable to find all values in statistics output.", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_PROG_ERROR);

        &my_die("Couldn't find expected output file: $outputImage", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputImage);
        &my_die("Couldn't find expected output file: $outputMask", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputMask);
        &my_die("Couldn't find expected output file: $outputWeight", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputWeight);
        &my_die("Couldn't find expected output file: $outputSources", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputSources);
        &my_die("Couldn't find expected output file: $outputPSF", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputPSF);
#    &my_die("Couldn't find expected output file: $outputBin1", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputBin1);
#    &my_die("Couldn't find expected output file: $outputBin2", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputBin2);
    }
}

unless ($no_update) {
    # XXX change -tess_id to -tess_dir when db is updated
    my $command = "$warptool -addwarped -warp_id $warp_id -skycell_id $skycell_id -tess_id $tess_dir";
    $command .= " -ignore" if not $accept; # Completed succesfully, but can't produce product
    $command .= " -uri $outputImage -path_base $outroot" if $accept;
    $command .= $stats->cmdflags() if $accept;
    $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);
        warn("Unable to perform warptool -addwarped: $error_code\n");
        exit($error_code);
    }
}

sub my_die
{
    my $msg = shift;            # Warning message on die
    my $warp_id = shift;        # Warp identifier
    my $skycell_id = shift;     # Skycell identifier
    my $tess_dir = shift;        # Tesselation identifier
    my $exit_code = shift;      # Exit code to add

    warn($msg);
    if (defined $warp_id and defined $skycell_id and defined $tess_dir and not $no_update) {
	# XXX change -tess_id to -tess_dir when db is updated
        my $command = "$warptool -addwarped -warp_id $warp_id -skycell_id $skycell_id -tess_id $tess_dir -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 $status = $?;
    system("sync") == 0
        or die "failed to execute sync: $!" ;
    $? = $status;
}

__END__
