#!/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 DateTime;
my $mjd_start = DateTime->now->mjd;   # MJD of starting script

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

use IPC::Cmd 0.36 qw( can_run run );
use PS::IPP::Metadata::Config;
use PS::IPP::Config 1.01 qw( :standard );

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

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

# Parse the command-line arguments
my ( $exp_id, $chip_id, $class_id, $chip_imfile_id, $uri, $camera, $outroot, $dbname, $run_state, $reduction, $threads, $verbose,
     $no_update, $no_op, $redirect );
GetOptions(
    'exp_id=s'          => \$exp_id,    # Exposure identifier
    'chip_id=s'         => \$chip_id,   # Chiptool identifier
    'class_id=s'        => \$class_id,  # Class identifier
    'chip_imfile_id=s'  => \$chip_imfile_id, # Unique file identifier
    'uri|u=s'           => \$uri,       # Input FITS file
    'camera|c=s'        => \$camera,    # Camera
    'outroot|w=s'       => \$outroot,   # output file base name
    'dbname|d=s'        => \$dbname,    # Database name
    'reduction=s'       => \$reduction, # Reduction class
    'run-state=s'       => \$run_state, # current state of the run (new, update)
    'threads=s'         => \$threads,   # Number of threads to use for ppImage
    'verbose'           => \$verbose,   # Print to stdout
    'no-update'         => \$no_update, # Don't update the database?
    'no-op'             => \$no_op,     # Don't do any operations?
    'redirect-output'   => \$redirect,
    ) or pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage( -msg => "Required options: --exp_id --chip_id --class_id --uri --camera --outroot --run-state",
           -exitval => 3) unless
    defined $exp_id and
    defined $chip_id and
    defined $class_id and
    ## defined $chip_imfile_id and  XXX until this is added to the scheme, do not require it : 
    defined $uri and
    defined $camera and
    defined $outroot and
    defined $run_state;

$ipprc->define_camera($camera);

my $logDest = $ipprc->filename("LOG.IMFILE", $outroot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
$logDest .= ".update" if $run_state eq "update";

if ($redirect) {
    $ipprc->redirect_output($logDest);
    print STDOUT "\n\n";
    print STDOUT "Starting script $0 on $host\n\n";
    print STDOUT "COMMAND IS: @ARGV\n\n";
}

# Look for programs we need
my $missing_tools;
my $chiptool = can_run('chiptool') or (warn "Can't find chiptool" and $missing_tools = 1);
my $ppImage = can_run('ppImage') or (warn "Can't find ppImage" and $missing_tools = 1);
my $ppConfigDump = can_run('ppConfigDump') or (warn "Can't find ppConfigDump" 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);
}

# Recipes to use based on reduction class
$reduction = 'DEFAULT' unless defined $reduction;
my $recipe_ppImage = $ipprc->reduction($reduction, 'CHIP_PPIMAGE'); # Recipe to use for ppImage
my $recipe_psphot  = $ipprc->reduction($reduction, 'CHIP_PSPHOT'); # Recipe to use for psphot
unless ($recipe_ppImage and $recipe_psphot) {
    &my_die("Couldn't find selected reduction for CHIP_PPIMAGE and CHIP_PSPHOT: $reduction\n", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
}

my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files

&my_die("Couldn't find input file: $uri\n", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($uri);

# outroot examples (HOST components must be set)
# file://data/ipp004.0/gpc1/20080130
# neb:///ipp004-v1/gpc1/20080130
# neb:///*/gpc1/20080130 (volume not specified)

# check for existing directory, generate if needed
$ipprc->outroot_prepare($outroot);

my $image_id = $chip_imfile_id;
my $source_id = $ipprc->source_id($dbname, $PS_TABLE_ID_CHIP);

## these names are used in ppImage, and thus may be URIs
my $outputImage   = $ipprc->filename("PPIMAGE.CHIP",        $outroot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
my $outputMask    = $ipprc->filename("PPIMAGE.CHIP.MASK",   $outroot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
my $outputWeight  = $ipprc->filename("PPIMAGE.CHIP.WEIGHT", $outroot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
my $outputBin1    = $ipprc->filename("PPIMAGE.BIN1",        $outroot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
my $outputBin2    = $ipprc->filename("PPIMAGE.BIN2",        $outroot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
my $outputStats   = $ipprc->filename("PPIMAGE.STATS",       $outroot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
my $traceDest     = $ipprc->filename("TRACE.IMFILE",        $outroot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
my $configuration = $ipprc->filename("PPIMAGE.CONFIG",      $outroot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);

if ($run_state eq 'update') {
    $outputStats .= '.update';
    $traceDest .= '.update';
}

my $cmdflags;

# Run ppImage
unless ($no_op) {
    my $command;
    my $do_stats;

    if ($run_state eq "new") {
        $command  = "$ppImage -file $uri $outroot";
        $command .= " -recipe PPIMAGE $recipe_ppImage";
        $command .= " -recipe PSPHOT $recipe_psphot";
        $command .= " -threads $threads" if defined $threads;
        $command .= " -dbname $dbname" if defined $dbname;
	# $command .= " -image_id $image_id" if defined $image_id;
	# $command .= " -source_id $source_id" if defined $source_id;
        $command .= " -dumpconfig $configuration";
        $command .= " -tracedest $traceDest -log $logDest";
        $do_stats = 1;
    } else {
        $command  = "$ppImage -file $uri $outroot";
        $command .= " -ipprc $configuration";
        $command .= " -threads $threads" if defined $threads;
        $command .= " -dbname $dbname" if defined $dbname;
	# $command .= " -image_id $image_id" if defined $image_id;
	# $command .= " -source_id $source_id" if defined $source_id;
        $command .= " -tracedest $traceDest -log $logDest";
        $command .= " -Db PPIMAGE:PHOTOM FALSE";
    }
    if ($do_stats) {
        $command .= " -recipe PPSTATS CHIPSTATS";
        $command .= " -stats $outputStats";
    }

    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);
        &my_die("Unable to perform ppImage: $error_code", $exp_id, $chip_id, $class_id, $error_code);
    }

    ## get the ppImage recipe for this camera and CHIP reduction
    $command = "$ppConfigDump -camera $camera -dump-recipe PPIMAGE -recipe PPIMAGE $recipe_ppImage -";
    ( $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);
        &my_die("Unable to perform ppConfigDump: $error_code", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR);
    }
    my $recipeData = $mdcParser->parse(join "", @$stdout_buf) or
        &my_die("Unable to parse metadata config doc", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR);

    ## allow the output images to be optional, depending on the recipe / reduction class
    my $outputImageExpect = metadataLookupBool($recipeData, 'CHIP.FITS');
    if ($outputImageExpect) {
        &my_die("Couldn't find expected output file: $outputImage\n",  $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputImage);
    }

    my $outputMaskExpect = metadataLookupBool($recipeData, 'CHIP.MASK.FITS');
    if ($outputMaskExpect) {
        &my_die("Couldn't find expected output file: $outputMask\n",   $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputMask);
    }

    my $outputWeightExpect = metadataLookupBool($recipeData, 'CHIP.WEIGHT.FITS');
    if ($outputWeightExpect) {
        &my_die("Couldn't find expected output file: $outputWeight\n", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputWeight);
    }

    &my_die("Couldn't find expected output file: $outputBin1\n",   $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputBin1);
    &my_die("Couldn't find expected output file: $outputBin2\n",   $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($outputBin2);

    if ($do_stats) {
        my $outputStatsReal = $ipprc->file_resolve($outputStats);
        &my_die("Couldn't find expected output file: $outputStats", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless -f $outputStatsReal;

        # measure chip stats
        $command = "$ppStatsFromMetadata $outputStatsReal - CHIP_IMFILE";
        ( $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);
            &my_die("Unable to perform ppStatsFromMetadata: $error_code", $exp_id, $chip_id, $class_id, $error_code);
        }
        foreach my $line (@$stdout_buf) {
            $cmdflags .= " $line";
        }
        chomp $cmdflags;
    }
}

my $command;
if ($run_state eq 'new') {
    # command to update database
    $command = "$chiptool -addprocessedimfile";
    $command .= " -exp_id $exp_id";
    $command .= " -chip_id $chip_id";
    $command .= " -class_id $class_id";
    $command .= " -uri $outputImage";
    $command .= " -path_base $outroot";
    $command .= " -hostname $host" if defined $host;
    $command .= " -dbname $dbname" if defined $dbname;
    $command .= " $cmdflags";
    $command .= (" -dtime_script " . ((DateTime->now->mjd - $mjd_start) * 86400));
} else {
    $command = "$chiptool -tofullimfile";
    $command .= " -chip_id $chip_id";
    $command .= " -class_id $class_id";
    $command .= " -dbname $dbname" if defined $dbname;
}

# Add the processed file to 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 chiptool -addprocessedimfile: $error_code\n");
        exit($error_code);
    }
} else {
    print "skipping command: $command\n";
}

sub my_die
{
    my $msg = shift; # Warning message on die
    my $exp_id = shift; # Chiptool identifier
    my $chip_id = shift; # Chiptool identifier
    my $class_id = shift; # Class identifier
    my $exit_code = shift; # Exit code to add
    # run_state, outputImage, and outroot are globals

    carp($msg);
    if (defined $chip_id and defined $class_id and not $no_update) {
        my $command;
        if ($run_state eq 'new') {
            $command = "$chiptool -addprocessedimfile";
            $command .= " -exp_id $exp_id";
            $command .= " -uri $outputImage";
            $command .= " -path_base $outroot";
            $command .= " -hostname $host" if defined $host;
            $command .= (" -dtime_script " . ((DateTime->now->mjd - $mjd_start) * 86400));
        } else {
            $command .= "$chiptool -updateprocessedimfile";
        }
        $command .= " -chip_id $chip_id";
        $command .= " -class_id $class_id";
        $command .= " -code $exit_code";
        $command .= " -dbname $dbname" if defined $dbname;
        system ($command);
    }
    exit $exit_code;
}

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

__END__
