#!/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 Cache::File;
use Storable qw(freeze thaw);
use File::Basename qw( basename);
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
    );

my $ipprc = PS::IPP::Config->new(); # IPP configuration
use File::Spec;

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

my ($cache, $exp_tag, $class_id, $uri, $workdir, $dbname, $no_update, $no_op);

GetOptions(
    'caches'        => \$cache,
    'exp_tag|e=s'   => \$exp_tag,
    'class_id|i=s'  => \$class_id,
    'uri|u=s'       => \$uri,
    'workdir|w=s'   => \$workdir, # Working directory for output files
    'dbname|d=s'    => \$dbname,# Database name
    '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_tag --class_id --uri",
    -exitval => 3,
) unless defined $exp_tag 
    and defined $class_id 
    and defined $uri;

my $RECIPE = "PPSTATS_PHASE0"; # Recipe to use for ppStats

# These values should be constant for all components
# The key is the name in the ppStats output; the value is the switch for "phase0 -updateexp"
use constant CONSTANTS => {
    "FILE.LEVEL"   => "-filelevel", # File level
    "FPA.OBJECT"   => "-object", # Object
    "FPA.OBSTYPE"  => "-exp_type", # Exposure type
    "FPA.FILTER"   => "-filter", # Filter used
    "FPA.AIRMASS"  => "-airmass", # Airmass
    "FPA.RA"       => "-ra",        # Right ascension
    "FPA.DEC"      => "-decl",        # Declination
    "FPA.ALT"      => "-alt",        # Altitude
    "FPA.AZ"       => "-az",        # Azimuth
    "FPA.POSANGLE" => "-posang", # Position angle
    "FPA.TIME"     => "-dateobs", # Date of observation (UTC)
    };

# These values may vary across components; we will take the average
# The key is the name in the ppStats output; the value is the switch for "phase0 -updateexp"
use constant VARIABLES => {
    "CHIP.TEMP"    => "-ccd_temp", # CCD temperature
    "CELL.EXPOSURE" => "-exp_time" # Exposure time
    };


# Look for programs we need
my $missing_tools;
my $regtool = can_run('regtool')
    or (warn "Can't find regtool" and $missing_tools = 1);
my $ppStats = can_run('ppStats')
    or (warn "Can't find ppStats" and $missing_tools = 1);

if ($missing_tools) { 
    warn ("Can't find required tools");
    exit($PS_EXIT_CONFIG_ERROR); 
}

# setup cache interface

my $c = Cache::File->new(
    cache_root => File::Spec->catdir($ENV{'HOME'}, '.pxtools', basename($0)),
    default_expires => '7200 sec',
);

# Run ppStats on the input file
my $stats;
{
    my $command = "$ppStats $uri -recipe PPSTATS $RECIPE -level"; # Command to run ppStats
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        cache_run(command => $command, verbose => 1);
    unless ($success) { 
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
        warn ("Unable to perform ppStats on exposure id $exp_tag: $error_code");
        &my_die ($exp_tag, $class_id, $error_code);
    }
    
    # Parse the output
    my $mdcParser = PS::IPP::Metadata::Config->new;        # Parser for metadata config files
    my $metadata = $mdcParser->parse(join "", @$stdout_buf); # XXX is this join necessary?
    unless ($metadata) {
        warn ("Unable to parse metadata config doc");
        &my_die ($exp_tag, $class_id, $PS_EXIT_PROG_ERROR);
    }
    my @constants = keys %{CONSTANTS()}; # List of constants to parse out
    my @variables = keys %{VARIABLES()}; # List of variables to parse out
    $stats = PS::IPP::Metadata::Stats->new(\@constants, \@variables); # Stats parser
    unless ($stats->parse($metadata)) {
        warn ("Unable to find all values");
        &my_die ($exp_tag, $class_id, $PS_EXIT_CONFIG_ERROR);
    }

    if (0) {
	# XXX for a test, randomly declare a failure and return to pantasks
	my $rnd = rand(1);
	if ($rnd > 0.5) {
	    warn ("random failure");
	    &my_die ($exp_tag, $class_id, $PS_EXIT_DATA_ERROR);
	}
    }
}

# Push the results into the database
unless ($no_update) {
    my $command = "$regtool -addprocessedimfile -exp_tag $exp_tag -class_id $class_id"; # Command to run regtool

    foreach my $constant (keys %{CONSTANTS()}) {
	my $value = ($stats->data($constant))->{value};
	if ($value =~ /\s/) {
	    # Quote arguments with whitespace
            $value = "\'$value\'";
        }
        $command .=  ' ' . CONSTANTS->{$constant} . ' ' . $value;
    }

    foreach my $variable (keys %{VARIABLES()}) {
        # Just use the mean value
        $command .= ' ' . VARIABLES->{$variable} . ' ' . ($stats->data($variable))->{mean};
    }

    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');
    $command .= " -bg $bg -bg_stdev $bg_stdev -bg_mean_stdev $bg_mean_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);
        # If we can't run -addprocessedimfile, we can't actually set the error code. If this is not
	# a database error, it is probably a programming error (in regtool or the passed args)
        warn ("Unable to perform regtool -addprocessedimfile: $error_code");
        exit($error_code);
    }
}

sub cache_run
{
    my %p = @_;

    my $cmd_output = $c->get($p{command}) if $cache;
    if (defined $cmd_output) {
        return @{thaw $cmd_output};
    } else {
        my @output = run(%p);
        $c->set($p{command}, freeze \@output) if $cache;
        return @output;
    }
}

sub my_die
{
    my $exp_tag = $_[0];
    my $class_id = $_[1];
    my $exit_code = $_[2];
    if ($exp_tag && $class_id and not $no_update) {
	my $command = "$regtool -addprocessedimfile -exp_tag $exp_tag -class_id $class_id -code $exit_code";
	$command .= " -dbname $dbname" if defined $dbname;
        system ($command);
    }
    exit $exit_code;
}

# Pau.

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

__END__
