#!/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::Cmd 0.36 qw( can_run run );
use PS::IPP::Config 1.01 qw( :standard );
use PS::IPP::Metadata::Config;

my $PI = 3.141592653589793238462643383279502;

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

$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

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

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 $command = "$ppStats $uri -recipe PPSTATS $RECIPE -level | $ppStatsFromMetadata - - REGISTER_IMFILE"; # Command to run ppStats and ppStatsFromMetadata
    $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);
        &my_die ("Unable to perform ppStats on exposure id $exp_id: $error_code", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $error_code);
    }
    foreach my $line (@$stdout_buf) {
	$cmdflags .= " $line";
    }
    chomp $cmdflags;
}

$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 ) =
        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 = 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__
