#!/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 $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 ($listFile, $listName) = tempfile( "$tess_id.$skycell_id.wrp$warp_id.list.XXXX", UNLINK => 1);
foreach my $imfile (@$imfiles) {
    print $listFile ( $imfile->{uri} . "\n");
}
close $listFile;

# Run pswarp
my $stats = PS::IPP::Metadata::Stats->new(); # Stats parser
unless ($no_op) {
    my $command = "$pswarp -list $listName $outputRoot $skyFile -stat $outputStats"; # Command to run pswarp
    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, $error_code);
    }
    &my_die("Couldn't find expected output file: $outputImage", $warp_id, $skycell_id, $tess_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($outputImage);
    &my_die("Couldn't find expected output file: $outputStats", $warp_id, $skycell_id, $tess_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($outputStats);
#    &my_die("Couldn't find expected output file: $outputBin1", $warp_id, $skycell_id, $tess_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($outputBin1);
#    &my_die("Couldn't find expected output file: $outputBin2", $warp_id, $skycell_id, $tess_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($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 $metadata = $mdcParser->parse(join "", @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"; # 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__
