#!/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 Data::Dumper;
use File::Temp qw( tempfile );

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 Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );

my ($stack_id, $dbname, $workdir, $no_update, $no_op);
GetOptions(
    'stack_id|d=s'      => \$stack_id, # Stack identifier
    '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: --stack_id",
    -exitval => 3,
	  ) unless defined $stack_id;

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

# Get list of components for stacking
my $mdcParser = PS::IPP::Metadata::Config->new;	# Parser for metadata config files
my $files;
{
    my $command = "$stacktool -inputskyfile -stack_id $stack_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 stacktool -inputskyfile: $error_code", $stack_id, $error_code);
    }

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

&my_die("Subtraction list contains more than two elements", $stack_id, $PS_EXIT_SYS_ERROR) unless
    scalar @$files >= 2;

# Parse the list of input files to get the tesselation, skycell identifiers and camera
my $skycell_id;			# Skycell identifier
my $tess_id;			# Tesselation identifier
my $camera;			# Camera
foreach my $file (@$files) {
    if (defined $tess_id) {
	&my_die("Tesselation identifiers don't match", $stack_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", $stack_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", $stack_id, $PS_EXIT_SYS_ERROR) unless $file->{camera} eq $camera;
    } else {
	$camera = $file->{camera};
    }
}

&my_die("Can't find camera", $stack_id, $PS_EXIT_SYS_ERROR) unless $camera;
$ipprc->define_camera($camera);

# Generate MDC file with the inputs
my ($listFile, $listName) = tempfile( "$tess_id.$skycell_id.stk$stack_id.list.XXXX", UNLINK => 1 );
my $num = 0;
foreach my $file (@$files) {
    print $listFile "INPUT$num\tMETADATA\n";
    $num++;

    my $image = $file->{uri};	# Image name
    my $mask = $ipprc->filename( "PSWARP.OUTPUT.MASK", $file->{path_base} ); # Mask name

    &my_die("Image $image does not exist", $stack_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists( $image );
    &my_die("Mask $mask does not exist", $stack_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists( $mask );
   
    print $listFile "\tIMAGE\tSTR\t" . $image . "\n";
    print $listFile "\tMASK\tSTR\t" . $mask . "\n"; 

    ### XXX NEED TO UPDATE THESE appropriately
    print $listFile "\tSEEING\tF32\t" . 1.0 . "\n";
    print $listFile "\tWEIGHT\tF32\t" . 1.0 . "\n";
    print $listFile "\tSCALE\tF32\t" . 1.0 . "\n";

    print $listFile "END\n\n";
}

# Get the output filenames
$workdir = caturi( $workdir, "tess_" . $tess_id, "sky_" . $skycell_id ) if defined $workdir;
my $outputRoot = $ipprc->file_prepare( "$tess_id.$skycell_id.stk$stack_id", $workdir, $$files[0]->{uri} );
my $outputName = $ipprc->filename("PPSTACK.OUTPUT", $outputRoot);
my $outputMask = $ipprc->filename("PPSTACK.OUTPUT.MASK", $outputRoot);
#my $bin1Name =  $ipprc->filename("PPSTACK.BIN1", $outputRoot);
#my $bin2Name =  $ipprc->filename("PPSTACK.BIN2", $outputRoot);
my $outputStats = $outputRoot . '.stats';

# Perform stacking
my $stats = PS::IPP::Metadata::Stats->new(); # Stats parser
unless ($no_op) {
    my $command = "$ppStack $listName $outputRoot";
    $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 ppImage: $error_code", $stack_id, $error_code);
    }
    &my_die("Couldn't find expected output file: $outputName", $stack_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputName);
    &my_die("Couldn't find expected output file: $outputMask", $stack_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputMask);
#    &my_die("Couldn't find expected output file: $bin1Name",    $stack_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($bin1Name);
#    &my_die("Couldn't find expected output file: $bin2Name",    $stack_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($bin2Name);
    &my_die("Couldn't find expected output file: $outputStats", $stack_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputStats);

    # Get the statistics on the stacked image
    my $statsFile;		# File handle
    open $statsFile, $ipprc->file_resolve($outputStats) or &my_die("Can't open statistics file $outputStats: $!", $stack_id, $PS_EXIT_SYS_ERROR);
    my @contents = <$statsFile>; # Contents of file
    close $statsFile;
    my $metadata = $mdcParser->parse(join "", @contents) or
	&my_die("Unable to parse metadata config doc", $stack_id, $PS_EXIT_PROG_ERROR);
    $stats->parse($metadata) or &my_die("Unable to find all values in statistics output.", $stack_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) {

    # Add the stack result
    {
	my $command = "$stacktool -addsumskyfile -stack_id $stack_id -uri $outputName -path_base $outputRoot";
	$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);
	    &my_die("Unable to perform stacktool -addsumskyfile: $error_code", $stack_id, $error_code);
	}
    }

    # Register the run as completed
    {
	my $command = "$stacktool -updaterun -stack_id $stack_id -state stop"; # Command to run stacktool
	$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 stacktool -updaterun: $error_code\n");
	    exit($error_code);
	}
    }
}


sub my_die
{
    my $msg = shift;		# Warning message on die
    my $stack_id = shift;	# Stack identifier
    my $exit_code = shift;	# Exit code to add

    warn($msg);
    if ($stack_id and not $no_update) {
	my $command = "$stacktool -updaterun -stack_id $stack_id -state stop -code $exit_code";
	$command .= " -dbname $dbname" if defined $dbname;
###        system ($command);
    }
    exit $exit_code;
}

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

__END__
