#!/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 Cache::File;
use Storable qw(freeze thaw);
use File::Basename qw( basename);
use IPC::Run;
use IPC::Cmd 0.36 qw( can_run );
use PS::IPP::Config 1.01 qw( :standard );
use PS::IPP::Metadata::Config;
use Math::Trig;

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

# 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);
my $ppStatsFromMetadata = can_run( 'ppStatsFromMetadata' ) or (warn "Can't find ppStatsFromMetadata" and $missing_tools = 1);

my ($cache, $exp_id, $tmp_class_id, $tmp_exp_name, $uri, $dbname, $verbose, $no_update, $no_op, $logfile);
GetOptions(
    'caches'           => \$cache,
    'exp_id|e=s'       => \$exp_id,
    'tmp_class_id|i=s' => \$tmp_class_id,
    'tmp_exp_name|n=s' => \$tmp_exp_name,
    'uri|u=s'          => \$uri,
    'dbname|d=s'       => \$dbname,    # Database name
    'verbose'          => \$verbose,   # Print to stdout
    'no-update'        => \$no_update,
    'no-op'            => \$no_op,
    'logfile=s'        => \$logfile,
) or pod2usage( 2 );

# Unhandled exceptions should be passed on to my_die so they get pushed into the database
$SIG{__DIE__} = sub { die @_ if $^S;
                      my_die( $_[0], $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_UNKNOWN_ERROR ); };

$ipprc->redirect_output($logfile) if $logfile;

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


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

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

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

my $now_time = localtime();
printf STDERR "\nstarting ppStats: %s\n", $now_time if $verbose;

my $cmdflags;
# Run ppStats on the input file
{
    my $command1 = "$ppStats $uri -recipe PPSTATS $RECIPE -level";
    my $command2 = "$ppStatsFromMetadata - - REGISTER_IMFILE";

    # Since there are no spaces in the arguments, we can get away with this:
    my @command1 = split(/ /, $command1);
    my @command2 = split(/ /, $command2);

    # Run ppStats
    my ($in1, $out1, $err1);    # Buffers for ppStats
    my $h1 = IPC::Run::harness \@command1, \$in1, \$out1, \$err1;
    print "[Running $command1]\n";
    my $result1 = IPC::Run::run $h1;
    print "STDOUT:\n$out1";
    print "STDERR:\n$err1";
    &my_die("Unable to perform ppStats on exposure id $exp_id: " . $h1->result(), $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $h1->result() ) unless $result1;

    print "[Running " . join(' ', @command2) . "]\n";
    my ($out2, $err2);          # Buffers for ppStatsFromMetadata
    my $h2 = IPC::Run::harness \@command2, \$out1, \$out2, \$err2;
    print "[Running $command2]\n";
    my $result2 = IPC::Run::run $h2;
    print "STDOUT:\n$out2";
    print "STDERR:\n$err2";
    &my_die("Unable to perform ppStatsFromMetadata on exposure id $exp_id: " . $h2->result(), $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $h2->result() ) unless $result2;
    chomp $out2;
    $cmdflags = $out2;
}

$now_time = localtime();
printf STDERR "\ndone with ppStats: %s\n", $now_time if $verbose;

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

my $command = "$regtool -addprocessedimfile";
$command .= " -exp_id $exp_id";
$command .= " -exp_name $tmp_exp_name"; # keep the supplied exp_name (could be derived from the file)
$command .= " -tmp_class_id $tmp_class_id"; # the original class_id supplied by the user, replace by ppStats CLASS.ID
$command .= " -uri $uri ";
$command .= " -hostname $host" if defined $host;
$command .= " -dbname $dbname" if defined $dbname;
$command .= " $cmdflags";

# determine solar-system parameters
my $longitude = &value_for_flag ($cmdflags, "-longitude");
my $latitude  = &value_for_flag ($cmdflags, "-latitude");
my $elevation = &value_for_flag ($cmdflags, "-elevation");
my $ra        = &value_for_flag ($cmdflags, "-ra");
my $dec       = &value_for_flag ($cmdflags, "-decl");
my $dateobs   = &value_for_flag ($cmdflags, "-dateobs");

# if the needed data is available, pass it to sunmoon:
if ($longitude && $latitude && $ra && $dec && $dateobs) {

    $longitude *= 12.0 / pi; # longitude is reported in West radians; sunmoon wants it in West Hours
    $latitude *= 180.0 / pi; # latitude is reported in North radians; sunmoon wants it in North Degrees
    $ra *= 180.0 / pi; # ra is reported in radians; sunmoon wants it in degrees
    $dec *= 180.0 / pi; # dec is reported in radians; sunmoon wants it in degrees

    my $sunmoon_cmd = "sunmoon -latitude $latitude -longitude $longitude -elevation $elevation $dateobs $ra $dec";
    my $sunmoon_data = `$sunmoon_cmd`;
    chomp $sunmoon_data;

    # print STDERR "run: $sunmoon_cmd\n";
    # print STDERR "got: $sunmoon_data\n";

    if ($?) {
        warn ("failure running $sunmoon_cmd, not supplying\n");
    } else {
        $command .= " $sunmoon_data";
    }
}

$now_time = localtime();
printf STDERR "\nrunning regtool update: %s\n", $now_time if $verbose;

# Push the results into the database
unless ($no_update) {
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        IPC::Cmd::run(command => $command, verbose => $verbose);
    unless ($success) {
        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
        warn ("Unable to perform regtool -addprocessedimfile: $error_code");
        exit($error_code);
    }
} else {
    print "skipping command: $command\n";
}

$now_time = localtime();
printf STDERR "\ndone with regtool update: %s\n", $now_time if $verbose;

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 = IPC::Cmd::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 $exp_name = shift;
    my $tmp_class_id = shift;
    my $uri = shift;
    my $exit_code = shift;

    # for failed imfiles, we insert UNKNOWN for inst, telescope, class_id

    carp($msg);
    if (defined $exp_id && defined $tmp_class_id and not $no_update) {
        my $command = "$regtool -addprocessedimfile";
        $command .= " -exp_id $exp_id";
        $command .= " -exp_name $exp_name";
        $command .= " -tmp_class_id $tmp_class_id";
        $command .= " -uri $uri ";
        $command .= " -telescope UNKNOWN";
        $command .= " -inst UNKNOWN";
        $command .= " -class_id $tmp_class_id";
        $command .= " -code $exit_code";
        $command .= " -hostname $host" if defined $host;
        $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__
