#!/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 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);

# print "args: @ARGV\n";
# for (my $i = 0; $i < @ARGV; $i++) {
#   print "arg $i: ...$ARGV[$i]...\n";
# }

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
) 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
# use constant 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 => {
    "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
    };


# Switches for regtool
use constant REGTOOL_MODE => '-addprocessedimfile'; # Mode for regtool
use constant REGTOOL_EXPTAG => '-exp_tag'; # Switch to specify the exposure id
use constant REGTOOL_CLASSID => '-class_id'; # Switch to specify the class id
use constant REGTOOL_BG_MEAN => '-bg'; # Switch to add the background
use constant REGTOOL_BG_STDEV => '-bg_stdev'; # Switch to add the bg stdev
use constant REGTOOL_BG_MEAN_STDEV => '-bg_mean_stdev'; # Switch to add the bg mean stdev

# 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',
);

# Resolve the input URI
$uri = $ipprc->convert_filename_absolute($uri);

# Run ppStats on the input file
my $stats;
{
    my $command = "$ppStats $uri -recipe PPSTATS $RECIPE"; # 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_PROG_ERROR);
        # XXX is this a programming or a 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;
    push @command, $regtool, REGTOOL_MODE(), REGTOOL_EXPTAG(), $exp_tag, REGTOOL_CLASSID(), $class_id; # Command to run regtool

    foreach my $constant (keys %{CONSTANTS()}) {
        push @command, CONSTANTS->{$constant}, ($stats->data($constant))->{value};

    }
    foreach my $variable (keys %{VARIABLES()}) {
        # Just use the mean value
        push @command, VARIABLES->{$variable}, ($stats->data($variable))->{mean};
    }
    
    push @command, REGTOOL_BG_MEAN();
    if (defined $stats->bg_mean()) {
        push @command, $stats->bg_mean();
    } else {
        push @command, "NAN";
    }
    push @command, REGTOOL_BG_STDEV();
    if (defined($stats->bg_stdev())) {
        push @command, $stats->bg_stdev();
    } else {
        # Will not be defined if there is only a single imfile
        push @command, 0;
    }
    push @command,  REGTOOL_BG_MEAN_STDEV();
    if (defined $stats->bg_mean_stdev()) {
        push @command, $stats->bg_mean_stdev();
    } else {
        push @command, "0.0";
    }

    # Quote arguments with whitespace
    for (my $i = 0; $i < scalar @command; $i++) {
        if ($command[$i] =~ /\s/) {
            $command[$i] = "\'$command[$i]\'";
        }
    }

    push @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);
        # XXX if we can't run -addprocessedimfile, we can't actually set the
        # error code.
        # XXX 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__
