#!/bin/env perl
###
#
# create a postage stamp request
#
###

use warnings;
use strict;

use Carp;
use Getopt::Long qw( GetOptions );
use Sys::Hostname;
use File::Copy;
use POSIX qw( strftime );

my $host = hostname();
my $verbose = 0;
my $dbname;
my $dbserver;
my $tmp_req_file;
my $workdir;

GetOptions(
    'tmp_req_file=s'=>  \$tmp_req_file,
    'workdir=s'     =>  \$workdir,
    'dbname=s'      =>  \$dbname,
    'dbserver=s'    =>  \$dbserver,
    'verbose'       =>  \$verbose,
);

die "required arguments --tmp_req_file --workdir --dbname --dbserver"
    if( !defined($tmp_req_file) or !defined($workdir) or !defined ($dbname)
        or !defined($dbserver));
use IPC::Cmd 0.36 qw( can_run run );

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

use Cwd;

my $cwd = cwd();

my $missing_tools;

my $pstamptool = can_run('pstamptool')  or (warn "Can't find pstamptool"  and $missing_tools = 1);
my $pstampdump = can_run('pstampdump')  or (warn "Can't find pstampdump"  and $missing_tools = 1);

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

my ($extname, $extver, $req_name);
{
    my $command = "$pstampdump -headeronly $tmp_req_file";
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    unless ($success) {
        print STDERR @$stderr_buf;
        exit $error_code >> 8;
    }
    my $output = join "", @$stdout_buf;
    ($extname, $extver, $req_name) = split " ", $output;
    if ($extname and ($extname ne "PS1_PS_REQUEST")) {
        print STDERR "invalid request file\n";
        exit $PS_EXIT_DATA_ERROR;
    }
    if (!defined $req_name) {
        print STDERR "invalid request file no REQ_NAME\n";
        exit $PS_EXIT_DATA_ERROR;
    }
}

my $datestr = strftime "%Y%m%d", gmtime;
my $datedir = "$workdir/webreq/$datestr";
if (! -e $datedir ) {
    if (!  mkdir $datedir ) {
        print STDERR  "failed to create working directory $datedir";
        exit $PS_EXIT_CONFIG_ERROR;
    }
}

my $webreq_num = get_webreq_num();
my $req_file = "$datedir/web_$webreq_num.fits";

if (!copy( $tmp_req_file, $req_file)) {
    die("Unable to copy request file $tmp_req_file to $req_file");
}

# Queue the request
my $req_id = 0;
{

    my $command = "$pstamptool -addreq -name $req_name -uri $req_file -ds_id 0";
    $command .= " -dbname $dbname" if $dbname;
    $command .= " -dbserver $dbserver" if $dbserver;
    $command .= " -label WEB.UP";
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    unless ($success) {
        my $errbuf = join "", @$stderr_buf;
        print STDERR $errbuf;
        if ($errbuf =~ /Duplicate entry/) {
            print "Request Name $req_name has already been used";
            exit $PS_EXIT_DATA_ERROR;
        } else {
            exit $PS_EXIT_UNKNOWN_ERROR;
        }
    }
    $req_id = ${$stdout_buf}[0];
}

print "$req_id $req_name\n";

exit 0;

# Temporary hack
# webrequest number is stored in a file in the current directory
#
# get this number from the database
sub get_webreq_num
{
    my $filename = "$workdir/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;
}
