#!/bin/env perl
###
#
# pstampwebrequest.pl: take a postage stamp request command line and process it
#
# The arguments are the command line parameters for the program pstamprequest
#
# Unless the argument -list is provided the output is the request id for the resulting request
#
# If -list is the first argument, the request file is built and parsed and the
# the selected "input" uris are listed on stdout.
#
# Note: Despite the name there nothing particularly web specific about this program.
#
###

use warnings;
use strict;

use Getopt::Long qw( GetOptions );
use Sys::Hostname;

my $host = hostname();
my $verbose = 0;
my $dbname;
my $project;
my $job_type;

GetOptions(
    'job_type=s'    =>  \$job_type,
    'dbname=s'      =>  \$dbname,
    'project=s'     => \$project,
    'verbose'       => \$verbose,
);



if ($verbose) {
    print "\n\n";
    print "Starting script $0 on $host\n\n";
}

my $listMode;
if ($job_type and ($job_type eq 'list_uri')) {
    $listMode=1;
} else  {
    $listMode=0;
}


use IPC::Cmd 0.36 qw( can_run run );

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

use Cwd;

my $missing_tools;

my $pstamprequest = can_run('pstamprequest')  or (warn "Can't find pstamprequest"  and $missing_tools = 1);
my $pstamptool = can_run('pstamptool')  or (warn "Can't find pstamptool"  and $missing_tools = 1);
my $pstampparse = can_run('pstampparse.pl')  or (warn "Can't find pstampparse.pl"  and $missing_tools = 1);
my $pstampparser_run = can_run('pstamp_parser_run.pl')  or (warn "Can't find pstamp_parser_run.pl"  and $missing_tools = 1);

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

# make a request file
my $cur_dir = getcwd();
#print STDERR "cur_dir is $cur_dir\n";
my $request_name = "web" . get_webreq_num();
my $request_file = "$cur_dir/$request_name.fits";
{
    my $command = "$pstamprequest -req_name $request_name -project $project $request_file @ARGV";
    $command .= " -$job_type" if $job_type;     # default job_type is pstamp

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    unless ($success) {
        print STDERR @$stderr_buf;
        die("Unable to perform pstamprequest: $error_code");
    }
}

# ok at this point we have a request file add it to the database (unless we're in listMode)
if ($listMode == 1 ) {
    ###
    ### In list mode just parse the file print the output and we're done
    ###
    my $command = "$pstampparse --mode list_uri --file $request_file";
    $command .= " --dbname $dbname" if $dbname;
    $command .= " --verbose" if $verbose;
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);

    if ($success) {
        ### print "Matching Images:\n";
        print @$stdout_buf;
        exit 0;
    } else {
        # we send the output to STDOUT because that's where PHP finds it
        print @$stdout_buf;
        print @$stderr_buf;
        exit 1;
    }
}

# Queue the request
my $req_id = 0;
{

    my $command = "$pstamptool -addreq -uri $request_file -ds_id 0";
    $command .= " -dbname $dbname" if $dbname;
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    unless ($success) {
        print STDERR @$stderr_buf;
        die("Unable to perform pstamptool -addreq: $error_code");
    }
    $req_id = ${$stdout_buf}[0];
}

print "$req_id";

exit 0;

# Temporary hack
# webrequest number is stored in a file in the current directory
#
sub get_webreq_num
{
    my $filename = "webreq_num.txt";
    if (! open IN, "+< $filename" ) {
        my $initial_num = 1;
        open IN, "> $filename" or die "can't open $filename";
        print IN "$initial_num\n" or die "failed to initialize $filename";
        close IN;
        return $initial_num;
    }

    my $webreq_num = <IN>;
    chomp $webreq_num;

    print STDERR "$webreq_num\n" if $verbose;

    my $next = $webreq_num + 1;
    truncate IN, 0;
    seek IN, 0, 0;
    print IN "$next\n";

    close IN;
    return $webreq_num;
}
