#!/usr/bin/env perl

use Carp;
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::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 );

# Parse the command-line arguments
my ($exp_id, $chip_id, $class_id, $input_uri, $exp_tag, $camera, $dbname, $workdir, $reduction, $no_update, $no_op);
GetOptions(
	   'exp_id=s'      => \$exp_id,    # Exposure identifier		       
	   'chip_id=s'     => \$chip_id,   # Chiptool identifier		       
	   'class_id=s'    => \$class_id,  # Class identifier		       
	   'input_uri|u=s' => \$input_uri, # Input FITS file		       
	   'camera|c=s'    => \$camera,	   # Camera			       
	   'dbname|d=s'    => \$dbname,    # Database name
	   'exp_tag=s'     => \$exp_tag,    # Exposure identifier		       
	   'workdir|w=s'   => \$workdir,   # Working directory, for output files  
	   'reduction=s'   => \$reduction, # Reduction class		       
	   '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: --exp_id --exp_tag --chip_id --class_id --uri --camera",
	   -exitval => 3) unless
    defined $exp_id and
    defined $chip_id and
    defined $class_id and
    defined $input_uri and
    defined $exp_tag and
    defined $camera;

$ipprc->define_camera($camera);

# Recipes to use based on reduction class
$reduction = 'DEFAULT' unless defined $reduction;
my $recipe = $ipprc->reduction($reduction, 'CHIP'); # Recipe to use
unless ($recipe) {
    &my_die("Couldn't find selected reduction for CHIP: $reduction\n", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
}

# values to extract from output metadata and the stats to calculate
my $STATS = 
   [   
       #          PPSTATS KEYWORD         STATISTIC          CHIPTOOL FLAG
       { name => "ROBUST_MEDIAN",  type => "mean",  flag => "-bg",             dtype => "float" },
       { name => "ROBUST_MEDIAN",  type => "stdev", flag => "-bg_mean_stdev",  dtype => "float" },
       { name => "ROBUST_STDEV",   type => "rms",   flag => "-bg_stdev",       dtype => "float" },
       { name => "FRINGE_0",       type => "rms",   flag => "-fringe_0",       dtype => "float" },
       { name => "FRINGE_RESID_0", type => "rms",   flag => "-fringe_1",       dtype => "float" },
       { name => "FRINGE_ERR_0",   type => "rms",   flag => "-fringe_2",       dtype => "float" },
       { name => "OVER_VAL",       type => "mean",  flag => "-bias", 	       dtype => "float" },
       { name => "FWHM",           type => "mean",  flag => "-fwhm", 	       dtype => "float" },
       { name => "APMIFIT",        type => "mean",  flag => "-ap_resid",       dtype => "float" },
       { name => "DAPMIFIT",       type => "rms",   flag => "-ap_resid_stdev", dtype => "float" },
       { name => "CERROR",         type => "rms",   flag => "-sigma_ra",       dtype => "float" },
       { name => "CERROR",         type => "rms",   flag => "-sigma_dec",      dtype => "float" },
       { name => "NSTARS",         type => "sum",   flag => "-n_stars",        dtype => "int"   },
       { name => "NASTRO",         type => "sum",   flag => "-n_astrom",       dtype => "int"   },
   ];
my $stats = PS::IPP::Metadata::Stats->new($STATS); # Stats parser

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

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

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

my $outputRoot  = $ipprc->file_prepare( "$exp_tag.ch.$chip_id", $workdir, $input_uri );

my $outputImage = $ipprc->filename("PPIMAGE.CHIP",      $outputRoot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
my $outputMask  = $ipprc->filename("PPIMAGE.CHIP.MASK", $outputRoot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
my $outputWeight  = $ipprc->filename("PPIMAGE.CHIP.WEIGHT", $outputRoot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
my $outputBin1  = $ipprc->filename("PPIMAGE.BIN1",      $outputRoot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
my $outputBin2  = $ipprc->filename("PPIMAGE.BIN2",  	$outputRoot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
my $outputStats = $ipprc->filename("PPIMAGE.STATS", 	$outputRoot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);

# Run ppImage
unless ($no_op) {
    my $command = "$ppImage -file $input_uri $outputRoot";
    $command .= " -recipe PPIMAGE $recipe";
    $command .= " -recipe PPSTATS CHIPSTATS";
    $command .= " -stats $outputStats";
    $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 ppImage: $error_code", $exp_id, $chip_id, $class_id, $error_code);
    }

    &my_die("Couldn't find expected output file: $outputImage\n", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputImage);
    &my_die("Couldn't find expected output file: $outputMask\n",  $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputMask);
    &my_die("Couldn't find expected output file: $outputWeight\n",  $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputWeight);
    &my_die("Couldn't find expected output file: $outputBin1\n",  $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputBin1);
    &my_die("Couldn't find expected output file: $outputBin2\n",  $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputBin2);
    &my_die("Couldn't find expected output file: $outputStats\n", $exp_id, $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: $!", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR);
    my @contents = <$statsFile>; # Contents of file
    close $statsFile;

    # parse the statistics MDC file
    my $mdcParser = PS::IPP::Metadata::Config->new();	# Parser for metadata config files
    my $metadata = $mdcParser->parse(join "", @contents);
    unless ($metadata) {
	&my_die("Unable to parse metadata config doc", $exp_id, $chip_id, $class_id, $PS_EXIT_PROG_ERROR);
    }

    # extract the stats from the metadata
    unless ($stats->parse($metadata)) {
	&my_die("Failure extracting metadata from the statistics output file.\n", $exp_id, $chip_id, $class_id, $PS_EXIT_PROG_ERROR);
    }
}

# command to update database
my $command = "$chiptool -addprocessedimfile";
$command .= " -exp_id $exp_id";
$command .= " -chip_id $chip_id";
$command .= " -class_id $class_id";
$command .= " -uri $outputImage";
$command .= " -path_base $outputRoot";
$command .= " -dbname $dbname" if defined $dbname;
$command .= $stats->cmdflags();

# Add the processed file to the database
unless ($no_update) {
    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);
    }
} else {
    print "skipping command: $command\n";
}

sub my_die
{
    my $msg = shift; # Warning message on die
    my $exp_id = shift; # Chiptool identifier
    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 .= " -exp_id $exp_id";
	$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__
