#!/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 File::Temp qw( tempfile );
use File::Basename qw( basename );
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::List qw( parse_md_list );

use PS::IPP::Config 1.01 qw( :standard );

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 arguments
my ($dist_id, $stage, $stage_id, $clean, $outroot);
my ($dbname, $save_temps, $verbose, $no_update, $no_op, $logfile);

GetOptions(
           'dist_id=s'  => \$dist_id,# Magic destreak run identifier
           'stage=s'        => \$stage,      # raw, chip, warp, or diff
           'stage_id=s'     => \$stage_id,   # exp_id, chip_id, warp_id, or diff_id
           'outroot=s'      => \$outroot,    # "directory" for outputs
           'save-temps'     => \$save_temps, # Save temporary files?
           'dbname=s'       => \$dbname,     # Database name
           'verbose'        => \$verbose,    # Print stuff?
           'no-update'      => \$no_update,  # Don't update the database?
           'no-op'          => \$no_op,      # Don't do any operations?
           'logfile=s'      => \$logfile,
           ) or pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage( -msg => "Required options: --dist_id --stage --stage_id --outroot",
           -exitval => 3) unless
    defined $dist_id and
    defined $stage and
    defined $stage_id and
    defined $outroot;

$ipprc->redirect_output($logfile) if $logfile;

# Look for programs we need
my $missing_tools;
my $disttool   = can_run('disttool') or (warn "Can't find disttool" and $missing_tools = 1);
my $regtool   = can_run('regtool') or (warn "Can't find regtool" and $missing_tools = 1);
my $chiptool   = can_run('chiptool') or (warn "Can't find chiptool" and $missing_tools = 1);
my $camtool   = can_run('camtool') or (warn "Can't find camtool" and $missing_tools = 1);
my $faketool   = can_run('faketool') or (warn "Can't find faketool" and $missing_tools = 1);
my $warptool   = can_run('warptool') or (warn "Can't find warptool" and $missing_tools = 1);
my $difftool   = can_run('difftool') or (warn "Can't find difftool" and $missing_tools = 1);
my $stacktool   = can_run('stacktool') or (warn "Can't find stacktool" and $missing_tools = 1);
if ($missing_tools) {
    &my_die("Can't find required tools.", $dist_id, $PS_EXIT_CONFIG_ERROR);
}

my $mdcParser = PS::IPP::Metadata::Config->new;

my $tool;
if ($stage eq "raw") {
    $tool = "regtool";
} elsif ($stage eq "chip") {
    $tool = "chiptool";
} elsif ($stage eq "camera") {
    $tool = "camtool";
} elsif ($stage eq "fake") {
    $tool = "faketool";
} elsif ($stage eq "warp") {
    $tool = "warptool";
} elsif ($stage eq "stack") {
    $tool = "stacktool";
} elsif ($stage eq "diff") {
    $tool = "difftool";
} else {
    &my_die("Unexpected stage: $stage", $dist_id, $PS_EXIT_CONFIG_ERROR);
}

# XXX Should we create a file rule for this
my $outfile = "$outroot/dbinfo.$stage.$stage_id.mdc";

{
    my $id_arg = "-$stage" . "_id";
    my $command = "$tool -exportrun $id_arg $stage_id -outfile $outfile";
    $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 $command: $error_code", $dist_id, $error_code);
    }
}

# set distRun.stage = 'full'
{
    my $command = "$disttool -updaterun -dist_id $dist_id -set_state full";
    $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 $command: $error_code", $dist_id, $error_code);
    }
}


exit 0;

### Pau.


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

    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;

    my $command = "$disttool -updaterun";
    $command   .= " -dist_id $dist_id";
    $command   .= " -code $exit_code";
    $command   .= " -dbname $dbname" if defined $dbname;

    # Add the processed file to the database
    unless ($no_update) {
        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
            run(command => $command, verbose => $verbose);
        unless ($success) {
            carp("failed to update database for $dist_id");
        }
    } else {
        print "Skipping command: $command\n";
    }

    carp($msg);
    exit $exit_code;
}

__END__
