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

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

my ($det_id, $iter, $class_id, $det_type, $camera, $dbname, $workdir, $no_update, $no_op, $quiet);
GetOptions(
    'det_id|d=s'        => \$det_id,
    'iteration=s'       => \$iter,
    'class_id|i=s'      => \$class_id,
    'det_type|t=s'      => \$det_type,
    'camera|c=s'        => \$camera,
    'dbname|d=s'        => \$dbname, # Database name
    'workdir|w=s'       => \$workdir,	# Working directory, for output files
    'no-update'         => \$no_update,
    'no-op'             => \$no_op,
    'quiet'             => \$quiet,
) or pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage( -msg => "Required options: --det_id --iteration --class_id --det_type --camera", -exitval => 3 ) 
    unless defined $det_id
    and defined $iter
    and defined $class_id
    and defined $det_type
    and defined $camera;

my $verbose = 1;
if (defined $quiet) { $verbose = 0; }

# Recipes to use as a function of detrend type
use constant RECIPES => {
    'bias' => 'PPMERGE_BIAS',
    'dark' => 'PPMERGE_DARK',
    'shutter' => 'PPMERGE_SHUTTER',
    'flat' => 'PPMERGE_FLAT',
    'domeflat' => 'PPMERGE_FLAT',
    'skyflat' => 'PPMERGE_FLAT',
    'fringe' => 'PPMERGE_FRINGE',
    };

# Look for programs we need
my $missing_tools;
my $dettool = can_run('dettool') or (warn "Can't find dettool" and $missing_tools = 1);
my $ppMerge = can_run('ppMerge') or (warn "Can't find ppMerge" and $missing_tools = 1);
if ($missing_tools) { 
    warn("Can't find required tools.");
    exit($PS_EXIT_CONFIG_ERROR); 
}

my $recipe = RECIPES()->{lc($det_type)}; # Recipe to use in stacking
&my_die("Unrecognised detrend type: $det_type", $det_id, $iter, $class_id, $PS_EXIT_PROG_ERROR) unless defined $recipe;

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

# Get list of files to stack
my $files;			# Array of files to be stacked
{
    my $command = "$dettool -processedimfile -det_id $det_id -class_id $class_id -included"; # Command to run
    $command .= " -dbname $dbname" if defined $dbname;
    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 dettool -processedimfile: $error_code", $det_id, $iter, $class_id, $error_code);
    }
    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
	&my_die("Unable to parse metadata config doc", $det_id, $iter, $class_id, $PS_EXIT_PROG_ERROR);
    $files = parse_md_list($metadata) or 
	&my_die("Unable to parse metadata list", $det_id, $iter, $class_id, $PS_EXIT_PROG_ERROR);
}

$workdir = caturi( $workdir, "$camera.$det_type.$det_id" ) if defined $workdir;

my $outputRoot = $ipprc->file_prepare( "$camera.$det_type.$det_id.$iter.$class_id", $workdir, ${$files}[0]->{uri} );
my $outputStack = $outputRoot . '.fits'; # Output name
my $outputStats = $outputRoot . '.stats'; # Statistics name

# Stack the files
my $stats = PS::IPP::Metadata::Stats->new(); # Stats parser
unless ($no_op) {
    my $command = "$ppMerge $outputStack"; # Command to run
    foreach my $file (@$files) {
	$command .= ' ' . $file->{uri};
    }
    $command .= " -recipe PPMERGE $recipe";
    $command .= ' -type ' . uc($det_type); # Type of stacking to perform
    $command .= " -stats $outputStats";	# Statistics output filename
    $command .= " -recipe PPSTATS CHIPSTATS";
    
    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 ppMerge: $error_code", $det_id, $iter, $class_id, $error_code);
    }
    &my_die("Unable to find expected output file: $outputStack\n", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($outputStack);
    &my_die("Unable to find expected output file: $outputStats\n", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($outputStats);

    # Get the statistics on the stacked image
    open(my $statsFile, $ipprc->file_resolve("$outputStats")) or
	&my_die("Can't open statistics file $outputStats: $!", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR);
    my $contents = do { local $/; <$statsFile> }; # Contents of file
    close($statsFile);
    
    my $mdcParser = PS::IPP::Metadata::Config->new;	# Parser for metadata config files
    my $metadata = $mdcParser->parse($contents) or
	&my_die("Unable to parse metadata config doc", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR);
    $stats = PS::IPP::Metadata::Stats->new(); # Stats parser
    $stats->parse($metadata)  or
	&my_die("Unable to find all values in statistics output.", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR);
}

my $bg = ($stats->bg_mean() or 'NAN');
my $bg_stdev = ($stats->bg_stdev() or 'NAN');
my $bg_mean_stdev = ($stats->bg_mean_stdev() or 'NAN');

# Add the resultant into the database
unless ($no_update) {
    my $command = "$dettool -addstacked -det_id $det_id -iteration $iter -class_id $class_id" .
	" -uri $outputStack -recip $recipe"; # Command to run
    $command .= " -bg $bg -bg_stdev $bg_stdev -bg_mean_stdev $bg_mean_stdev";
    $command .= " -dbname $dbname" if defined $dbname;

    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 dettool -addstacked: $error_code\n");
	exit($error_code);
    }
}


sub my_die
{
    my $msg = shift; # Warning message on die
    my $det_id = shift;		# Detrend identifier
    my $iter = shift;		# Iteration
    my $class_id = shift; # Class identifier
    my $exit_code = shift; # Exit code to add

    carp($msg);
    if ($det_id and $iter and $class_id and not $no_update) {
	my $command = "$dettool -addstacked -det_id $det_id -iteration $iter -class_id $class_id -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__
