#!/usr/bin/env perl

use Carp;
use warnings;
use strict;

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

use vars qw( $VERSION );
$VERSION = '0.01';

use Cache::File;
use Storable qw( freeze thaw );
use File::Basename qw( basename );
use File::Temp qw( tempfile );                   # tools to construct temp files
use IPC::Cmd 0.36 qw( can_run run );
use PS::IPP::Metadata::Config;
use PS::IPP::Config 1.01 qw( :standard );

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

# Look for commands we need
my $missing_tools;
my $regtool = can_run('regtool') or (warn "can't find regtool" and $missing_tools = 1);
my $ppStatsFromMetadata = can_run('ppStatsFromMetadata') or (warn "Can't find ppStatsFromMetadata" and $missing_tools = 1);
if ($missing_tools) {
    warn ("Can't find required tools");
    exit($PS_EXIT_CONFIG_ERROR);
}

my ($cache, $exp_id, $exp_tag, $label, $dvodb, $end_stage, $tess_id, $dbname, $verbose, $no_update, $no_op, $save_temps, $logfile);
GetOptions(
    'caches'        => \$cache,
    'exp_id|e=s'    => \$exp_id,
    'exp_tag|t=s'   => \$exp_tag,
    'dbname|d=s'    => \$dbname, # Database name
    'label=s'       => \$label,
    'dvodb=s'       => \$dvodb,
    'end_stage=s'   => \$end_stage,
    'tess_id=s'     => \$tess_id,
    'verbose'       => \$verbose,   # Print to stdout
    'no-update'     => \$no_update,
    'no-op'         => \$no_op,
    'save-temps'    => \$save_temps, # Save temporary files?
    'logfile=s'     => \$logfile,
) or pod2usage( 2 );

my $ipprc = PS::IPP::Config->new() or my_die( "Unable to set up", $exp_id, $PS_EXIT_CONFIG_ERROR );
$ipprc->redirect_output($logfile) or my_die( "Unable to redirect output", $exp_id, $PS_EXIT_SYS_ERROR ) if $logfile;

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

# add -detrend UNLESS type is one of SCIENCE listed below (eg, OBJECT)
my @SCIENCE = ( "object", "science", "light" ); # Observation types to NOT mark as detrend
my $DETREND_FLAG = "-end_stage reg"; # Flag to use to mark detrend exposure

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

my $cmdflags;

# Get the list of imfiles & their stats
{
    my $command = "$regtool -processedimfile -exp_id $exp_id";
    $command .= " -dbname $dbname" if defined $dbname;
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        cache_run(command => $command, verbose => $verbose);
    unless ($success) {
        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
        warn ("Unable to perform regtool -processedimfile on exposure id $exp_id: $error_code");
        exit ($error_code);
    }

    # since I can't figure out how to do input and output within PERL, I'm writing to a temp file
    my ($statFile, $statName) = tempfile( "/tmp/$exp_id.register.XXXX", UNLINK => !$save_temps );
    print "saving stats to $statName\n";
    foreach my $line (@$stdout_buf) {
        print $statFile $line;
    }
    close $statFile;

    # parse the stats in the metadata file
    $command = "$ppStatsFromMetadata $statName - REGISTER_EXP";
    ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    unless ($success) {
        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
        warn("Unable to perform ppStatsFromMetadata: $error_code\n");
        exit($error_code);
    }

    foreach my $line (@$stdout_buf) {
        $cmdflags .= " $line";
    }
    chomp $cmdflags;
}

# we require at a minimum: -telescope, -inst, -filelevel, -class_id, -exp_name, -exp_type
if (uc(&value_for_flag ($cmdflags, "-telescope")) eq "NULL") { &my_die ("telescope not found", $exp_id, $PS_EXIT_CONFIG_ERROR); }
if (uc(&value_for_flag ($cmdflags, "-inst"))      eq "NULL") { &my_die ("inst      not found", $exp_id, $PS_EXIT_CONFIG_ERROR); }
if (uc(&value_for_flag ($cmdflags, "-filelevel")) eq "NULL") { &my_die ("filelevel not found", $exp_id, $PS_EXIT_CONFIG_ERROR); }
if (uc(&value_for_flag ($cmdflags, "-exp_name"))  eq "NULL") { &my_die ("exp_name  not found", $exp_id, $PS_EXIT_CONFIG_ERROR); }

my $exp_type = &value_for_flag ($cmdflags, "-exp_type");
if (uc($exp_type) eq "NULL") { &my_die ("exp_type  not found", $exp_id, $PS_EXIT_CONFIG_ERROR); }

my $command = "$regtool -addprocessedexp";
$command .= " -exp_id $exp_id";
$command .= " -exp_tag $exp_tag";
$command .= " -hostname  $host"      if defined $host;
$command .= " -dbname    $dbname"    if defined $dbname;
$command .= " -label     $label"     if defined $label;
$command .= " -dvodb     $dvodb"     if defined $dvodb;
$command .= " -end_stage $end_stage" if defined $end_stage;
$command .= " -tess_id   $tess_id"   if defined $tess_id;
$command .= " -state full";
$command .= " $cmdflags";

# Add the detrend flag, if needed
{
    my $object = 0;             # Is it an object exposure?
    foreach my $scienceType (@SCIENCE) {
        if (lc($exp_type) =~ /$scienceType/) {
            $object = 1;
            last;
        }
    }
    $command .= " $DETREND_FLAG" unless $object;
}

# Output results to the database
unless ($no_update) {
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        cache_run(command => $command, verbose => $verbose);
    unless ($success) {
        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
        warn ("Unable to run regtool -addprocessedexp for $exp_id: $error_code");
        exit($error_code);
    }
} else {
    print "skipping command: $command\n";
}

### Pau.

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 value_for_flag
{
    my $cmdflags = shift;
    my $flag = shift;

    my $value = 0.0;
    if ($cmdflags =~ m|$flag|) {
        ($value) = $cmdflags =~ m|$flag\s+(\S+)|;
    }
    $value;
}

sub my_die
{
    my $msg = shift; # Warning message on die
    my $exp_id = shift;
    my $exit_code = shift;

    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;

    carp($msg);
    if (defined $exp_id and not $no_update) {
        my $command = "$regtool -addprocessedexp -exp_id $exp_id -fault $exit_code";
        $command .= " -hostname $host" if defined $host;
        $command .= " -dbname $dbname" if defined $dbname;
        system($command);
    }
    exit $exit_code;
}

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