#!/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 PS::IPP::Config qw($PS_EXIT_SUCCESS
		       $PS_EXIT_UNKNOWN_ERROR
		       $PS_EXIT_SYS_ERROR
		       $PS_EXIT_CONFIG_ERROR
		       $PS_EXIT_PROG_ERROR
		       $PS_EXIT_DATA_ERROR
		       $PS_EXIT_TIMEOUT_ERROR
		       caturi
		       );
my $ipprc = PS::IPP::Config->new(); # IPP configuration
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 );

my ($warp_id, $skycell_id, $tess_id, $camera, $dbname, $workdir, $no_update, $no_op);
GetOptions(
    'warp_id|i=s'       => \$warp_id, # Warp identifier
    'skycell_id|s=s'    => \$skycell_id, # Skycell identifier
    'tess_id|s=s'       => \$tess_id, # Tesselation identifier
    'camera|c=s'        => \$camera, # Camera name
    'dbname|d=s'        => \$dbname, # Database name
    'workdir|w=s'       => \$workdir, # Working directory, for output files
    '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: --warp_id --skycell_id --tess_id --camera",
    -exitval => 3,
) unless defined $warp_id
    and defined $skycell_id
    and defined $tess_id
    and defined $camera;

$ipprc->define_camera($camera);

# 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);
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;
{
    my $command = "$warptool -scmap -warp_id $warp_id -skycell_id $skycell_id -tess_id $tess_id";
    $command .= " -dbname $dbname" if defined $dbname;
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => 1);
    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_id, $error_code);
    }

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

$workdir = caturi( $workdir, "tess_" . $tess_id, "sky_" . $skycell_id ) if defined $workdir;
my $outputRoot = $ipprc->file_prepare( "$tess_id.$skycell_id.wrp$warp_id", $workdir, $$imfiles[0]->{uri} );
my $outputImage = $ipprc->filename("PSWARP.OUTPUT", $outputRoot, $skycell_id );
my $outputMask = $ipprc->filename("PSWARP.OUTPUT.MASK", $outputRoot, $skycell_id);
my $outputBin1 = $ipprc->filename("PSWARP.BIN1", $outputRoot, $skycell_id );
my $outputBin2 = $ipprc->filename("PSWARP.BIN2", $outputRoot, $skycell_id );
my $outputStats = $outputRoot . '.stats';
my $skyFile = caturi( $workdir, $skycell_id ); # Target sky cell file

# Get list of filenames
my ($list1File, $list1Name) = tempfile( "$tess_id.$skycell_id.wrp$warp_id.image.list.XXXX", UNLINK => 1);
my ($list2File, $list2Name) = tempfile( "$tess_id.$skycell_id.wrp$warp_id.mask.list.XXXX", UNLINK => 1);
my $inputAstrom;
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 $astrom = $ipprc->filename("PSASTRO.OUTPUT.MEF", $imfile->{cam_path_base}); # Astrometry file name

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

    print $list1File ( $image . "\n");
    print $list2File ( $mask  . "\n");
    if (defined $inputAstrom) {
	&my_die("Astrometry files don't match: $inputAstrom vs $astrom", $warp_id, $skycell_id, $tess_id, $PS_EXIT_SYS_ERROR) unless $inputAstrom eq $astrom;
    } else {
	$inputAstrom = $astrom;
    }
}
close $list1File;
close $list2File;

# Run pswarp
my $stats = PS::IPP::Metadata::Stats->new(); # Stats parser
unless ($no_op) {
    my $command = "$pswarp -list $list1Name";
    $command .= " -masklist $list2Name";
    $command .= " -astrom $inputAstrom";
    $command .= " $outputRoot $skyFile";
    $command .= " -stats $outputStats";
    $command .= " -recipe PPSTATS CHIPSTATS";

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => 1);
    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_id, $error_code);
    }
    &my_die("Couldn't find expected output file: $outputImage", $warp_id, $skycell_id, $tess_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputImage);
    &my_die("Couldn't find expected output file: $outputMask", $warp_id, $skycell_id, $tess_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputMask);
    &my_die("Couldn't find expected output file: $outputStats", $warp_id, $skycell_id, $tess_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputStats);
#    &my_die("Couldn't find expected output file: $outputBin1", $warp_id, $skycell_id, $tess_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputBin1);
#    &my_die("Couldn't find expected output file: $outputBin2", $warp_id, $skycell_id, $tess_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputBin2);

    # 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;

    # Just in case the statistics was impossible to do, e.g., small overlap:
    if ($contents !~ /^\s*$/) {
	my $metadata = $mdcParser->parse($contents)
	    or &my_die("Unable to parse metadata config", $warp_id, $skycell_id, $tess_id, $PS_EXIT_PROG_ERROR);
	$stats->parse($metadata) or &my_die("Unable to find all values in statistics output.", $warp_id, $skycell_id, $tess_id, $PS_EXIT_PROG_ERROR);
    }
}

# Add the processed file to the database
my $bg = ($stats->bg_mean() or 'NAN');
my $bg_stdev = ($stats->bg_stdev() or 'NAN');
unless ($no_update) {
    my $command = "$warptool -addwarped -warp_id $warp_id -skycell_id $skycell_id -tess_id $tess_id" .
	" -uri $outputImage -path_base $outputRoot"; # -path_base $outputRoot"; # Command to run dettool
    $command .= " -bg $bg -bg_stdev $bg_stdev";
    $command .= " -dbname $dbname" if defined $dbname;

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => 1);
    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_id = shift;	# Tesselation identifier
    my $exit_code = shift;	# Exit code to add

    warn($msg);
    if ($warp_id and $skycell_id and $tess_id and not $no_update) {
	my $command = "$warptool -addwarped -warp_id $warp_id -skycell_id $skycell_id -tess_id $tess_id -code $exit_code";
	$command .= " -dbname $dbname" if defined $dbname;
###        system ($command);
    }
    exit $exit_code;
}

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

__END__
