#!/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 vars qw( $VERSION );
$VERSION = '0.01';

use IPC::Cmd qw( can_run run );
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::Stats;
use PS::IPP::Metadata::List qw( parse_md_list );

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

my ($warp_id, $camera, $dbname, $workdir, $no_update, $no_op);
GetOptions(
    'warp_id|i=s'       => \$warp_id, # Warp identifier
    'camera|c=s'        => \$camera, # Camera name
    '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: --warp_id",
    -exitval => 3,
) unless defined $warp_id
    and defined $camera;

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

# Get list of component imfiles for exposure
my $imfiles;
{
    my $command = "$warptool -imfile -warp_id $warp_id";
    $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);
	&my_die("Unable to perform warptool -imfile: $error_code", $warp_id, $error_code);
    }

    my $mdcParser = PS::IPP::Metadata::Config->new;	# Parser for metadata config files
    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
	&my_die("Unable to parse metadata config doc", $warp_id, $PS_EXIT_PROG_ERROR);
    $imfiles = parse_md_list($metadata) or 
	&my_die("Unable to parse metadata list", $warp_id, $PS_EXIT_PROG_ERROR);
}

unless ($no_op) {

### Calculates, in some as-yet unknown way the overlaps between imfiles and skycells

} else {
    # Add in the skycell and tesselation for each imfile
    foreach my $imfile (@$imfiles) {
	$imfile->{skycell_id} = 'default';
	$imfile->{tess_id} = 'default';
	$imfile->{fault} = 0;
    }
}

if (defined $workdir) {
    $workdir = $ipprc->convert_filename_absolute( $workdir );
} else {
    my $example = $ipprc->convert_filename_absolute( $$imfiles[0]->{uri} );
    my ($vol, $dir, $file) = File::Spec->splitpath( $example );
    $workdir = $dir;
}

# Generate a MDC file with the overlaps
my $overlapName = File::Spec->catfile( $workdir, $warp_id . '.overlap.mdc' );
open my $overlapFile, "> $overlapName" or die "Unable to open mdc file $overlapName";
print $overlapFile "warpSkyCellMap MULTI\n\n";
foreach my $imfile (@$imfiles) {
    print $overlapFile "warpSkyCellMap\tMETADATA\n";
    print $overlapFile "\twarp_id\tS32\t" . $warp_id . "\n";
    print $overlapFile "\tskycell_id\tSTR\t" . $imfile->{skycell_id} . "\n";
    print $overlapFile "\ttess_id\t\tSTR\t" . $imfile->{tess_id} . "\n";
    print $overlapFile "\texp_tag\t\tSTR\t" . $imfile->{exp_tag} . "\n";
    print $overlapFile "\tcam_version\tS32\t" . $imfile->{cam_version} . "\n";
    print $overlapFile "\tclass_id\t\tSTR\t" . $imfile->{class_id} . "\n";
    print $overlapFile "\tfault\tS16\t" . $imfile->{fault} . "\n";
    print $overlapFile "END\n\n";
}
close $overlapFile;

# Add the processed file to the database
unless ($no_update) {
    my $command = "$warptool -addoverlap -mapfile $overlapName"; # Command to run warptool
    $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 warptool -addoverlap: $error_code\n");
	exit($error_code);
    }

    unlink $overlapName;
}



sub my_die
{
    my $msg = shift;		# Warning message on die
    my $warp_id = shift;	# Warp identifier
    my $exit_code = shift;	# Exit code to add

    warn($msg);

    # No failure option on warptool for this mode, so just die.
    exit $exit_code;
}

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

__END__
