#!/usr/bin/env perl
#
# parse a MOPS_DETCTABILITY_QUERY table and create a results file
#
# Note: this file is currently only a placeholder which creates a fake response file
# and adds a completed job to the database
#

use strict;
use warnings;

use Getopt::Long qw( GetOptions );
use Pod::Usage qw( pod2usage );
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
		       );

my ($req_file, $req_id, $out_dir, $product, $mode, $dbname, $dbserver, $verbose, $save_temps);

#
# parse args
#

GetOptions(
        'file=s'          =>      \$req_file,
        'req_id=s'        =>      \$req_id,
        'out_dir=s'       =>      \$out_dir,
        'product=s'       =>      \$product,
        'mode=s'          =>      \$mode,
        'dbname=s'        =>      \$dbname,
        'dbserver=s'      =>      \$dbserver,
        'verbose'         =>      \$verbose,
        'save-temps'      =>      \$save_temps,
) or pod2usage(2);

my $err = "";

if (!$req_file) {
    $err .= "--file is required\n";
}
if (!$req_id) {
    $err .= "--req_id is required\n";
}
if (!$out_dir) {
    $err .="--out_dir is required\n";
}
if (!$product) {
    $err .="--product is required\n";
}


die $err if ($err);

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

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

if (!$dbserver) {
    my $ipprc = = PS::IPP::Config->new();
    $dbserver =  metadataLookupStr($ipprc->{_siteConfig}, 'PS_DBSERVER');
}

# get the query id and check the extname and version from the header
my $fields_output;
{
    my $command = "echo $req_file | $fields -x 0 EXTNAME EXTVER QUERY_ID";
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    
#   fields doesn't return zero when it succeeds
#    unless ($success) {
#        print STDERR @$stderr_buf;
#    }
    $fields_output = join "", @$stdout_buf;
}
my (undef, $extname, $extver, $req_name) = split " ", $fields_output;

die "$req_file is missing one of EXTNAME EXTVER or QUERY_ID" 
    if !(defined($extname) and defined($extver) and defined($req_name));

die "$req_file has EXTNAME $extname not MOPS_DETECTABILITY_QUERY table"
                if $extname ne         "MOPS_DETECTABILITY_QUERY";
die "$req_file is version $extver expecting 1" if $extver ne 1;

$out_dir .= "/$req_name";
if (! -e $out_dir ) {
    mkdir $out_dir or die "cannot create output directory $out_dir";
} elsif (! -d $out_dir ) {
    die "output fileset directory $out_dir exists but is not a directory";
}

#
# XXX Eventually we will parse the file here, to look up the list of input images to be processed
# and queue a job for each image.
# The request file will be one of the arguments. Each job will look at all rows and create entries
# in the response file the coordinates that overlap the image.
#
# In the meantime we don't parse the file here, pass it to the program fakedresponse.
# It creates a response file with a line for each row in the request file

my $response_file = "$out_dir/response.fits";
my $fault;
{
    my $command = "$fakedresponse --input $req_file --output $response_file --workdir $out_dir";
    $command .= " --save-temps" if $save_temps;
    $command .= " --verbose" if $verbose;

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    unless ($success) {
        warn("Unable to perform $command error code: $error_code");
    }
    $fault = $error_code >> 8;
}

my $job_id;
my $result;
{
    my $command = "$pstamptool -addjob -req_id $req_id -uri $req_file -outputBase $out_dir";
    $command .= " -job_type detect_query -state stop -fault $fault";
    $command .= " -rownum 0";
    $command .= " -dbname $dbname" if $dbname;
    $command .= " -dbserver $dbserver" if $dbserver;

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);

    if ($success) {
        $job_id = join "", @$stdout_buf;
        chomp $job_id;
        if ($job_id && -e $response_file) {
            rename $response_file, "$out_dir/response${job_id}.fits";
        }
        $result = 0;
    } else {
        warn("Unable to perform $command error code: $error_code");
        $result = $error_code >> 8;
    }
}


{
    my $command = "$pstamptool -updatereq -req_id $req_id -name $req_name -outProduct $product";
    $command .= " -fault $result" if $result;
    $command .= " -dbname $dbname" if $dbname;
    $command .= " -dbserver $dbserver" if $dbserver;

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    unless ($success) {
        die "$command failed";
    }
}
 
exit 0;
