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

# 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);
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 ($warp_id, $skycell_id, $warp_skyfile_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
    'warp_skyfile_id|s=s' => \$warp_skyfile_id, # Unique file 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 $warp_skyfile_id
    and defined $tess_dir
    and defined $camera
    and defined $outroot
    and defined $run_state;

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

my $logDest = $ipprc->filename("LOG.EXP", $outroot, $skycell_id) or my_die( "Unable to get log filename", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR );
$logDest .= ".update" if ($run_state eq 'update');

$ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR ) if $redirect;

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

# 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.VARIANCE", $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 $weight = $ipprc->filename("PPIMAGE.CHIP.VARIANCE", $imfile->{chip_path_base}, $imfile->{class_id}); # Mask name

    my $mask = $ipprc->filename("PSASTRO.OUTPUT.MASK", $imfile->{cam_path_base}, $imfile->{class_id}); # Mask name
    if (!$ipprc->file_exists($mask)) {
        print "Celestial mask $mask not found, using basic mask\n";
        $mask = $ipprc->filename("PPIMAGE.CHIP.MASK", $imfile->{chip_path_base}, $imfile->{class_id}); # Mask name
        &my_die("Couldn't find input file: $mask", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($mask);
    }

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

    # 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 $cmdflags;
my $accept = 1;                 # Accept the skycell?
my $do_stats;
unless ($no_op) {
    my $command = "$pswarp";
    $command .= " -list $imageName";
    $command .= " -masklist $maskName";
    $command .= " -variancelist $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 .= " -F SOURCE.PLOT.MOMENTS SOURCE.PLOT.SKY.MOMENTS";
    $command .= " -F SOURCE.PLOT.PSFMODEL SOURCE.PLOT.SKY.PSFMODEL";
    $command .= " -F SOURCE.PLOT.APRESID SOURCE.PLOT.SKY.APRESID";
    $command .= " -psf";        # Turn on PSF determination
    $command .= " -tracedest $traceDest -log $logDest";
    $command .= " -threads $threads" if defined $threads;
    $command .= " -dbname $dbname" if defined $dbname;
    $command .= " -image_id $warp_skyfile_id" if defined $warp_skyfile_id;
    $command .= " -source_id $source_id" if defined $source_id;
    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 $outputStatsReal = $ipprc->file_resolve($outputStats);
        &my_die("Couldn't find expected output file: $outputStats", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR) unless -f $outputStatsReal;

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

        if ($cmdflags =~ /-accept/) {
            &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);
        }

        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 .= " -uri $outputImage" if $accept;
            $command .= (" -dtime_script " . ((DateTime->now->mjd - $mjd_start) * 86400));
            $command .= " $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

    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;

    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__
