#!/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 Digest::MD5::File qw( file_md5_hex );
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 );


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

# Parse the command-line arguments
my ($stage, $stage_limit, $dist_root, $no_magic);
my ($dbname, $save_temps, $verbose, $no_update, $logfile);

GetOptions(
           'dist_root=s'    => \$dist_root,  # root of distribution work area
           'stage=s'        => \$stage,      # stage to queue
           'stage_limit=s'  => \$stage_limit,# maximum number of runs queued for each stage
           'no_magic'       => \$no_magic,   # queue runs without requiring magic
           'dbname=s'       => \$dbname,     # Database name
           'verbose'        => \$verbose,    # Print stuff?
           'no-update'      => \$no_update,  # Don't update the database
           'save-temps'     => \$save_temps, # Save temporary files?
           'logfile=s'      => \$logfile,
           ) or pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
if (0) {
pod2usage( -msg => "Required options: --stage",
           -exitval => 3) unless
    defined $stage;
}

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

if (!$dist_root) {
    $dist_root = metadataLookupStr($ipprc->{_siteConfig}, "DISTRIBUTION_ROOT");
    &my_die("failed to find DISTRIBUTION_ROOT in site configuration", $PS_EXIT_CONFIG_ERROR) if !$dist_root;
}

my ($day, $month, $year) = (localtime)[3,4,5];
my $datestr = sprintf "%04d%02d%02d", $year+1900, $month + 1, $day;

my $workdir = "$dist_root/$datestr";

print "workdir is $workdir\n";

# if stage is not supplied as an argument, loop over all stages
my @stages;
if ($stage) {
    push @stages, $stage;
} else {
    @stages = qw( raw chip camera fake warp diff stack);
}

# XXX: how shall we deal with labels?
my $label = 'proc';

foreach my $stage (@stages) {
    my $command = "$disttool -definebyquery -stage $stage -workdir $workdir";
    $command .= " -no_magic" if $no_magic;
    $command .= " -dry_run" if $no_update;
    $command .= " -limit $stage_limit" if $stage_limit;
    $command .= " -set_label $label";
    $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: $error_code", $error_code);
    }
    # display the output from the command
    print STDERR join "", @$stdout_buf if $verbose;
}

# queue rcRuns for any distRuns that have completed and have interested destinations
{
    my $command = "$disttool -queuercrun";
    $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: $error_code", $error_code);
    }
    # display the output from the command
    print STDERR join "", @$stdout_buf if $verbose;
}

exit 0;

sub my_die {
    my $msg = shift;
    my $fault = shift;

    print STDERR "$msg\n";

    exit $fault;
}

__END__
