#!/usr/bin/env perl

use warnings;
use strict;
use Carp;

## report the program and machine
use Sys::Hostname;
my $host = hostname();
print "\n\n";
print "Starting script $0 on $host\n\n";

use IPC::Cmd 0.36 qw( can_run run );
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::Stats;
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 Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );

my $RECIPE = 'PPIMAGE_OBDSFRA'; # Recipe to use

# Parse the command-line arguments
my ($exp_id,			# Exposure identifier
    $chip_id,			# Chiptool identifier
    $class_id,			# Class identifier
    $input,			# Input FITS file
    $recipe,			# Recipe to use
    $camera,			# Camera
    $dbname,			# Database name
    $workdir,			# Working directory, for output files
    $no_update,			# Don't update the database?
    $no_op,			# Don't do any operations?
    );
GetOptions(
	   'exp_id=s'      => \$exp_id,
	   'chip_id=s'     => \$chip_id,
	   'class_id=s'    => \$class_id,
	   'uri|u=s'       => \$input,
	   'recipe=s'      => \$recipe,
	   'camera|c=s'    => \$camera,
	   'dbname|d=s'    => \$dbname, # Database name
	   'workdir|w=s'   => \$workdir,
	   'no-update'     => \$no_update,
	   'no-op'         => \$no_op,
	   ) or pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage(
    -msg => "Required options: --exp_id --chip_id --class_id --uri --camera",
    -exitval => 3,
) unless defined $exp_id
    and defined $chip_id 
    and defined $class_id 
    and defined $input
    and defined $camera;

$ipprc->define_camera($camera);

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

&my_die("Couldn't find input file: $input\n", $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($input);

$workdir = caturi( $workdir, $exp_id ) if defined $workdir;

my $outputRoot = $ipprc->file_prepare( "$exp_id.chp$chip_id", $workdir, $input );
my $outputImage = $ipprc->filename("PPIMAGE.CHIP", $outputRoot, $class_id);
my $outputMask = $ipprc->filename("PPIMAGE.CHIP.MASK", $outputRoot, $class_id);
my $outputBin1 = $ipprc->filename("PPIMAGE.BIN1", $outputRoot, $class_id);
my $outputBin2 = $ipprc->filename("PPIMAGE.BIN2", $outputRoot, $class_id);
my $outputStats = $outputRoot  . '.' . $class_id . '.stats';

my $stats = PS::IPP::Metadata::Stats->new(); # Stats parser
unless ($no_op) {
    # Run ppImage
    print "outputImage: $outputImage\n";
    print "outputBin1: $outputBin1\n";
    print "outputStats: $outputStats\n";

    my $command = "$ppImage -file $input $outputRoot";
    $command .= " -recipe PPIMAGE $RECIPE";
    $command .= " -recipe PPSTATS CHIPSTATS";
    $command .= " -stats $outputStats"; # Command to run ppImage

    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", $chip_id, $class_id, $error_code);
    }

    &my_die("Couldn't find expected output file: $outputImage\n", $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputImage);
    &my_die("Couldn't find expected output file: $outputMask\n", $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputMask);
    &my_die("Couldn't find expected output file: $outputBin1\n", $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputBin1);
    &my_die("Couldn't find expected output file: $outputBin2\n", $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputBin2);
    &my_die("Couldn't find expected output file: $outputStats\n", $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputStats);

    # Get the statistics on the processed image
    my $statsFile;		# File handle
    open $statsFile, $ipprc->file_resolve($outputStats) or &my_die("Can't open statistics file $outputStats: $!", $chip_id, $class_id, $PS_EXIT_SYS_ERROR);
    my @contents = <$statsFile>; # Contents of file
    close $statsFile;
    my $mdcParser = PS::IPP::Metadata::Config->new;	# Parser for metadata config files
    my $metadata = $mdcParser->parse(join "", @contents) or
	&my_die("Unable to parse metadata config doc", $chip_id, $class_id, $PS_EXIT_PROG_ERROR);
    $stats->parse($metadata) or
	&my_die("Unable to find all values in statistics output.\n", $chip_id, $class_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');
my $bg_mean_stdev = ($stats->bg_mean_stdev() or 'NAN');

unless ($no_update) {
    # Command to run chiptool
    my $command = "$chiptool -addprocessedimfile";
    $command .= " -chip_id $chip_id";
    $command .= " -class_id $class_id";
    $command .= " -uri $outputImage";
    $command .= " -path_base $outputRoot";
    $command .= " -bg $bg -bg_stdev $bg_stdev -bg_mean_stdev $bg_mean_stdev";
    # XXX add sigma_ra, etc here
    $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 chiptool -addprocessedimfile: $error_code\n");
	exit($error_code);
    }
}


sub my_die
{
    my $msg = shift; # Warning message on die
    my $chip_id = shift; # Chiptool identifier
    my $class_id = shift; # Class identifier
    my $exit_code = shift; # Exit code to add

    carp($msg);
    if ($chip_id and $class_id and not $no_update) {
	my $command = "$chiptool -addprocessedimfile";
	$command .= " -chip_id $chip_id";
	$command .= " -class_id $class_id";
	$command .= " -code $exit_code";
	$command .= " -uri $outputImage";
	$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__
