#!/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::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 );

# Parse the command-line
my ($det_id, $iter, $class_id, $value, $input_uri, $camera, $det_type, $dbname, $workdir, $no_update, $no_op);
GetOptions(
    'det_id|d=s'        => \$det_id,     # Detrend ID				
    'iteration|n=s'	=> \$iter,	 # Iteration				
    'class_id|i=s'      => \$class_id,	 # Class ID				
    'value|v=s'		=> \$value,	 # Value to multiple (for normalisation)	
    'input_uri|u=s'     => \$input_uri,	 # Input file				
    'camera|c=s'        => \$camera,	 # Camera				
    'det_type|t=s'      => \$det_type,	 # Detrend type				
    'dbname|d=s'        => \$dbname,	 # Database name				
    'workdir|w=s'       => \$workdir, 	 # Working directory, for output files	
    'no-update'         => \$no_update,	 # Don't update the database		
    'no-op'             => \$no_op,	 # Don't do any operations               
    ) or pod2usage( 2 );
    
pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage( -msg => "Required options: --det_id --iteration --class_id --value --input_uri --camera --det_type",
	   -exitval => 3) 
    unless defined $det_id
    and defined $iter
    and defined $class_id
    and defined $value
    and defined $input_uri
    and defined $camera
    and defined $det_type;

$ipprc->define_camera($camera);

my $RECIPE_PPIMAGE = 'PPIMAGE_N'; # Recipe to use with ppImage
my $RECIPE_PPSTATS = 'CHIPSTATS'; # Recipe to use with ppStats

# values to extract from output metadata and the stats to calculate
my $STATS = 
   [   
       #          PPSTATS KEYWORD         STATISTIC          CHIPTOOL FLAG
       { name => "ROBUST_MEDIAN",  type => "mean",  flag => "-bg",            dtype => "float" },
       { name => "ROBUST_MEDIAN",  type => "stdev", flag => "-bg_mean_stdev", dtype => "float" },
       { name => "ROBUST_STDEV",   type => "rms",   flag => "-bg_stdev",      dtype => "float" },
   ];
my $stats = PS::IPP::Metadata::Stats->new($STATS); # Stats parser

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

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

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

my $outputRoot = $ipprc->file_prepare( "$camera.$det_type.norm.$det_id.$iter", $workdir, $input_uri );

my $output    = $ipprc->filename("PPIMAGE.OUTPUT", $outputRoot, $class_id);
my $b1name    = $ipprc->filename("PPIMAGE.BIN1",   $outputRoot, $class_id);
my $b2name    = $ipprc->filename("PPIMAGE.BIN2",   $outputRoot, $class_id);
my $statsName = $ipprc->filename("PPIMAGE.STATS",  $outputRoot, $class_id);

# Run normalisation
unless ($no_op) {
    my $command = "$ppImage -file $input_uri $outputRoot";
    $command .= " -norm $value -stats $statsName";
    $command .= " -recipe PPIMAGE $RECIPE_PPIMAGE";
    $command .= " -recipe PPSTATS $RECIPE_PPSTATS";
    $command .= ' -isfringe' if lc($det_type) eq 'fringe';

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => 1);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	&my_die("Unable to perform ppImage: $error_code", $det_id, $iter, $class_id, $error_code);
    }
    &my_die("Can't find expected output file: $output", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($output);
    &my_die("Can't find expected output file: $b1name", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($b1name);
    &my_die("Can't find expected output file: $b2name", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($b2name);
    &my_die("Can't find expected output file: $statsName", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($statsName);
    
    # Get the statistics on the normalised image
    my $statsFile; # File handle
    open $statsFile, $ipprc->file_resolve($statsName) or &my_die("Can't open statistics file $statsName: $!\n", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR);
    &my_die("Can't open statistics file $statsName: $!\n", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR) unless defined $statsFile;
    my @contents = <$statsFile>; # Contents of file
    close $statsFile;

    # parse the statistics MDC file
    my $mdcParser = PS::IPP::Metadata::Config->new;	# Parser for metadata config files
    my $metadata = $mdcParser->parse(join "", @contents);
    unless ($metadata) {
	&my_die("Unable to parse metadata config", $det_id, $iter, $class_id, $PS_EXIT_PROG_ERROR);
    }

    # extract the stats from the metadata
    unless ($stats->parse($metadata)) {
	&my_die("Unable to find all values in statistics output.", $det_id, $iter, $class_id, $PS_EXIT_PROG_ERROR);
    }
}

# Command to update the database
my $command = "$dettool -addnormalizedimfile";
$command .= " -det_id $det_id";
$command .= " -iteration $iter";
$command .= " -class_id $class_id";
$command .= " -uri $output";
$command .= " -path_base $outputRoot";
$command .= " -dbname $dbname" if defined $dbname;
$command .= $stats->cmdflags();

# Add the processed file to the database
unless ($no_update) {
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => 1);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	warn("Unable to perform dettool -addnormalizedimfile: $error_code\n");
	exit($error_code);
    }
} else {
    print "skipping command: $command\n";
}

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 -addnormalizedimfile";
	$command .= " -det_id $det_id";
	$command .= " -iteration $iter";
	$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__
