#!/bin/env perl
###
### pstamp_job_run.pl
###
###     Run a given postage stamp Job
###

use warnings;
use strict;

if (@ARGV != 1) {
    die "usage: $0 job_id\n";
}

my $job_id = $ARGV[0];

my $verbosity = 1;

use Sys::Hostname;
my $host = hostname();

print "\n\n";
print "Starting script $0 on $host\n\n";

use IPC::Cmd 0.36 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
		       metadataLookupStr
		       metadataLookupBool
		       caturi
		       );

my $missing_tools;

my $pstamptool = can_run('pstamptool')  or (warn "Can't find pstamptool"  and $missing_tools = 1);
my $ppstamp    = can_run('ppstamp') or (warn "Can't find ppstamp" and $missing_tools = 1);
my $pstamp_get_image_job    = can_run('pstamp_get_image_job.pl') or (warn "Can't find pstamp_get_image_job.pl" and $missing_tools = 1);

if ($missing_tools) {
    warn("Can't find required tools.");
    exit ($PS_EXIT_CONFIG_ERROR);
}

my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files

my $psjob;
#Look up the uri for the given job
{
    my $command = "$pstamptool -pendingjob -job_id $job_id";
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbosity);
    unless ($success) {
        die("Unable to perform pstamptool -pendingjob: $error_code");
    }

    if (@$stdout_buf == 0) {
        print STDERR "pending pstamp job id $job_id not found\n";
        exit 0;
    }
    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
        die("Unable to parse metdata config doc");

    my $jobs = parse_md_list($metadata);

    $psjob = ${@$jobs}[0];
}

if (!$psjob) {
    print STDERR "postage stamp job $job_id not found\n";
    exit 1;
}

my $uri = $psjob->{uri};
my $outputBase = $psjob->{outputBase};
my $argString = $psjob->{args};
my $jobType = $psjob->{jobType};

my $jobStatus;
if ($jobType eq "stamp") {
    my $command = "$ppstamp -file $uri $outputBase $argString";
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbosity);

    if ($success) {
        $jobStatus = $PS_EXIT_SUCCESS;
    } else {
        $jobStatus = $error_code >> 8;
        print STDERR "ppstamp failed with error code: $jobStatus\n";
    }
} elsif ($jobType eq "get_image") {
    my $command = "$pstamp_get_image_job --uri $uri --out_dir $outputBase";
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbosity);

    if ($success) {
        $jobStatus = $PS_EXIT_SUCCESS;
    } else {
        $jobStatus = $error_code >> 8;
        print STDERR "ppstamp failed with error code: $jobStatus\n";
    }
} else {
    die("unknown jobType $jobType found");
}


# stop the job and set the result value
{
    my $command = "$pstamptool -processedjob -job_id $job_id -state stop -result $jobStatus";
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbosity);
    unless ($success) {
        die("Unable to perform $command: $error_code");
    }
}

exit $jobStatus;
