#!/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 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 constant POIS_OPTIONS => '-v -B 1000';

use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );

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

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

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

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

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

# Identify the input and the template
my $input;			# Input file
my $template;			# Template file
my $tess_id;			# Tesselation identifier
my $skycell_id;			# Skycell identifier
my $camera;			# Camera
foreach my $file (@$files) {
    if (defined $file->{template} and $file->{template}) {
	$template = $file->{uri};
    } else {
	$input = $file->{uri};
    }
    if (defined $tess_id) {
	&my_die("Tesselation identifiers don't match", $diff_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", $diff_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", $diff_id, $PS_EXIT_SYS_ERROR) unless $file->{camera} eq $camera;
    } else {
	$camera = $file->{camera};
    }
}

&my_die("Unable to identify template", $diff_id, $PS_EXIT_SYS_ERROR) unless defined $template;
&my_die("Unable to identify input", $diff_id, $PS_EXIT_SYS_ERROR) unless defined $input;
&my_die("Unable to identify camera", $diff_id, $PS_EXIT_SYS_ERROR) unless defined $camera;
$ipprc->define_camera($camera);


# 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.dif$diff_id", $workdir, $input );
my $outputName = $outputRoot . ".fits";
my $bin1Name =  $ipprc->filename("PPIMAGE.BIN1", $outputRoot);
my $bin2Name =  $ipprc->filename("PPIMAGE.BIN2", $outputRoot);
my $outputStats = $outputRoot . '.stats';


### XXX We have to play around some here, because pois can't use Nebulous
my $outputNameResolved = $ipprc->file_create( $outputName );
my $templateResolved = $ipprc->file_resolve( $template );
my $inputResolved = $ipprc->file_resolve( $input );

# Perform subtraction
my $stats = PS::IPP::Metadata::Stats->new(); # Stats parser
unless ($no_op) {
    my $command = "$pois " . POIS_OPTIONS() . " $templateResolved $inputResolved $outputNameResolved"; # Command to run pois

    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", $diff_id, $error_code);
    }
    &my_die("Couldn't find expected output file: $outputName", $diff_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($outputName);
#    &my_die("Couldn't find expected output file: $bin1Name",    $diff_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($bin1Name);
#    &my_die("Couldn't find expected output file: $bin2Name",    $diff_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($bin2Name);
#    &my_die("Couldn't find expected output file: $outputStats", $diff_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($outputStats);

    # Get the statistics on the residual image
    if (0) { ### Disabled because pois doesn't output stats yet
	my $statsFile;		# File handle
	open $statsFile, $ipprc->file_resolve($outputStats) or &my_die("Can't open statistics file $outputStats: $!", $diff_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", $diff_id, $PS_EXIT_PROG_ERROR);
	$stats->parse($metadata) or &my_die("Unable to find all values in statistics output.", $diff_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 subtraction result
    {
	my $command = "$difftool -adddiffskyfile -diff_id $diff_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 difftool -adddiffskyfile: $error_code", $diff_id, $error_code);
	}
    }

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


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

    warn($msg);
    if ($diff_id and not $no_update) {
	my $command = "$difftool -updaterun -diff_id $diff_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__
