#!/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 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, $threads, $run_state, $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
    'threads=s'         => \$threads,   # Number of threads to use for pswarp
    'run-state=s'       => \$run_state,  # 'new' or 'update'
    '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 --run-state",
    -exitval => 3,
) unless defined $warp_id
    and defined $skycell_id
    and defined $tess_dir
    and defined $camera
    and defined $outroot
    and defined $run_state;

$ipprc->define_camera($camera);

my $logDest = $ipprc->filename("LOG.EXP", $outroot, $skycell_id);
$logDest .= ".update" if ($run_state eq 'update');

$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.SKY.SAVE", $outroot);
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 $configuration =  $ipprc->filename("PSWARP.CONFIG", $outroot, $skycell_id);

if ($run_state eq 'update') {
    $traceDest .= ".update";
    $outputStats .= ".update";
}

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);
## XXX this seems to have insufficient error checking: dvoImageExtract can fail to write and still return a valid exit status

# Get list of filenames
my $tempOutRoot = "/tmp/warp.$camera.$warp_id.$skycell_id";
my ($imageFile,  $imageName)  = tempfile( "$tempOutRoot.image.list.XXXX",  UNLINK => !$save_temps);
my ($maskFile,   $maskName)   = tempfile( "$tempOutRoot.mask.list.XXXX",   UNLINK => !$save_temps);
my ($weightFile, $weightName) = tempfile( "$tempOutRoot.weight.list.XXXX", UNLINK => !$save_temps);
my ($astromFile, $astromName) = tempfile( "$tempOutRoot.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);

    # Astrometry file: astrometry is done at the camera stage, and always results in a MEF file
    # XXX allow an option to use the image header astrometry?
    my $astrom = $ipprc->filename($astromSource, $imfile->{cam_path_base});

    &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";
        $wrote_astrom = 1;
    }
}
close $imageFile;
close $maskFile;
close $weightFile;
close $astromFile;


# Run pswarp
my $accept = 1;                 # Accept the skycell?
my $do_stats;
unless ($no_op) {
    my $command = "$pswarp";
    $command .= " -list $imageName";
    $command .= " -masklist $maskName";
    $command .= " -weightlist $weightName";
    $command .= " -astromlist $astromName";
    $command .= " $outroot $skyFile";
    $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 .= " -psf";        # Turn on PSF determination
    $command .= " -tracedest $traceDest -log $logDest";
    $command .= " -threads $threads" if defined $threads;
    $command .= " -dbname $dbname" if defined $dbname;
    if ($run_state eq 'new') {
        $command .= " -dumpconfig $configuration";
        $do_stats = 1;
    } else {
        $command .= " -ipprc $configuration";
    }
    if ($do_stats) {
        $command .= " -recipe PPSTATS WARPSTATS";
        $command .= " -stats $outputStats";
    }

    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);
    }

    if ($do_stats) {
        # 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");

        # $accept is set above based on the fraction of lit pixels
        # XXX for some files, there may not be enough stars to find a good psf.  these should be dropped as well
        if ($accept && !$ipprc->file_exists($outputPSF)) {
            $accept = 0;
        }

        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";
            $command .= " -warp_id $warp_id";
            $command .= " -skycell_id $skycell_id";
            $command .= " -tess_id $tess_dir";
            $command .= " -path_base $outroot"; # needed for logfile lookups
            $command .= " -ignore"           if not $accept; # Completed succesfully, but can't produce product
            $command .= " -uri $outputImage" if $accept;
            $command .= (" -dtime_script " . ((DateTime->now->mjd - $mjd_start) * 86400));
            $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);
            }
        }
    } else {
        # $run_state eq 'update'
        unless ($no_update) {
            my $command = "$warptool -tofullskyfile";
            $command .= " -warp_id $warp_id";
            $command .= " -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);
                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";
        if ($run_state eq 'new') {
            $command .= " -addwarped";
            $command .= " -tess_id $tess_dir";
            $command .= " -path_base $outroot";
            $command .= " -hostname $host" if defined $host;
        } else {
            $command .= " -updateskyfile";
        }
        $command .= " -warp_id $warp_id";
        $command .= " -skycell_id $skycell_id";
        $command .= (" -dtime_script " . ((DateTime->now->mjd - $mjd_start) * 86400));
        $command .= " -code $exit_code";
        $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__
