#! /usr/bin/env perl

use Carp;
use warnings;
use strict;

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::Config 1.01 qw( :standard );

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


# Hard coded values
my $remote_root = '/scratch3/watersc1/';

my $command_output
GetOptions(
    'command_output=s'  => \$command_output;
    ) or pod2usage( 2 );

open(LIST,$command_output);
while(<LIST>) {
    chomp;
    
    if ($_ =~ /ppImage/) {
	my $base = (split /\s+/)[15]; # This is super fragile.
	my $stats= $base . "." . $class_id . ".stats"; # no good idea how to get that.
	my $command = "";
	if (-e $stats) { 
	    my $stat_cmd = "ppStatsFromMetadata $stats - 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;
	    
	    # Need to get all these parameters.
	    $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 .= " -magicked $magicked" if $magicked;
	    $command .= " -hostname $host" if defined $host;
	    $command .= " -dbname $dbname" if defined $dbname;
	    $command .= " $cmdflags";
	    $command .= (" -dtime_script " . ((DateTime->now->mjd - $mjd_start) * 86400));
	    
	}
	else { # This job failed permanently
	    $command = "$chiptool -addprocessedimfile";
            $command .= " -exp_id $exp_id";
            $command .= " -uri $outputImage" if defined $outputImage;
            $command .= " -path_base $outroot";
            $command .= " -hostname $host" if defined $host;
            $command .= (" -dtime_script " . ((DateTime->now->mjd - $mjd_start) * 86400));
	    $command .= " -chip_id $chip_id";
	    $command .= " -class_id $class_id";
	    $command .= " -fault $exit_code";
	    $command .= " -dbname $dbname" if defined $dbname;
	}
	

#     if ($_ =~ /stask: error: .*: task .*: Exited with exit code/) {
# 	print " ";  # This needs to be smarter.
# 	exit(1);
#     }
}
close(LIST);

