#!/usr/bin/env perl

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 PS::IPP::Metadata::Stats;
use IPC::Cmd qw( can_run run );
use Data::Dumper;

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

# Parse the command-line
my ($det_id,                     # Detrend ID
    $iter,  			# Iteration
    $class_id,			# Class ID
    $value,			# Value to multiple (for normalisation)
    $input,			# Input file
    $camera,			# Camera
    $det_type,			# Detrend type
    $dbname,			# Database name
    $workdir,			# Working directory, for output files
    $no_update,			# Don't update the database
    $no_op,			# Don't do any operations
    );
GetOptions(
    'det_id|d=s'        => \$det_id,
    'iteration|n=s'	=> \$iter,
    'class_id|i=s'      => \$class_id,
    'value|v=s'		=> \$value,
    'input_uri|u=s'     => \$input,
    'camera|c=s'        => \$camera,
    'det_type|t=s'      => \$det_type,
    'dbname|d=s'        => \$dbname,
    'workdir|w=s'       => \$workdir, # Working directory, for output files
    'no-update'         => \$no_update,
    'no-op'             => \$no_op,
    ) 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
    and defined $camera
    and defined $det_type;

$ipprc->define_camera($camera);


use constant RECIPE => 'PPIMAGE_N'; # Recipe to use with ppImage

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

if (defined $workdir) {
    $workdir = $ipprc->convert_filename_absolute( $workdir );
} else {
    my ($vol, $dir, $file) = File::Spec->splitpath( $input );
    $workdir = $dir;
}
$input = $ipprc->convert_filename_absolute( $input );

# Output name
my $outputFile = "$camera.$det_type.norm.$det_id.$iter"; # Root name
my $outputSubD = "$camera.$det_type.$det_id";
my $outputRoot = File::Spec->catfile( $workdir, $outputSubD, $outputFile );

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 = $outputRoot . '.' . $class_id . '.stats'; # Statistics file

# Run normalisation
my $stats = PS::IPP::Metadata::Stats->new(); # Stats parser
unless ($no_op) {
    my $command = "$ppImage -file $input $outputRoot -norm $value -stat $statsName -recipe PPIMAGE " . RECIPE(); # Command to run
    $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 -e $output;
    &my_die("Can't find expected output file: $b1name", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR) unless -e $b1name;
    &my_die("Can't find expected output file: $b2name", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR) unless -e $b2name;
    &my_die("Can't find expected output file: $statsName", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR) unless -e $statsName;
    
    # Get the statistics on the normalised image
    my $statsFile;		# File handle
    open $statsFile, $statsName or &my_die("Can't open statistics file $statsName: $!\n", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR);
    my @contents = <$statsFile>; # Contents of file
    close $statsFile;
    my $mdcParser = PS::IPP::Metadata::Config->new;	# Parser for metadata config files
    my $metadata = $mdcParser->parse(join "", @contents)
	or &my_die("Unable to parse metadata config", $det_id, $iter, $class_id, $PS_EXIT_PROG_ERROR);
    $stats->parse($metadata) or &my_die("Unable to find all values in statistics output.", $det_id, $iter, $class_id, $PS_EXIT_PROG_ERROR);
}    

# Update the database
$output = $ipprc->convert_filename_relative( $output );
$outputRoot = $ipprc->convert_filename_relative( $outputRoot );

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

unless ($no_update) {
    my $command = "$dettool -addnormalizedimfile -det_id $det_id -iteration $iter -class_id $class_id ".
	"-uri $output -path_base $outputRoot"; # 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 => 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);
    }

    unlink $statsName;
}

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

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