#!/bin/env perl

use strict;
use warnings;

use File::Temp qw( tempfile );

#use DBI;
use IPC::Cmd 0.36 qw( can_run run );
#use PS::IPP::Metadata::Config;
use PS::IPP::Config 1.01 qw( :standard );

use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );


my ($rundir, $verbose, $save_temps);

GetOptions(
    'rundir=s'      => \$rundir,
    'verbose'       => \$verbose,
    'save-temps'    => \$save_temps,
) or pod2usage( 2 );

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

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

my $ipphome = "/home/panstarrs/ipp";
$rundir = "$ipphome/pstamp" if !$rundir;

chdir $rundir or die "failed to cd to $rundir";


my ($pts, $pantasks_script) = tempfile ('/tmp/pts.XXXX', UNLINK => !$save_temps);

print $pts "status\n";
print $pts "quit\n";
close $pts;

my $command = "$pantasks_client < $pantasks_script";
my  ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    run(command => $command, verbose => $verbose);
unless ($success) {
    $error_code = (($error_code >> 8) or 1);
    if ($error_code == 12) {
        print "Postage Stamp Server is not running\n";
        exit 0;
    }
    warn("$command failed. exit status: $error_code");
    exit $error_code;
}

my $output = join "", @$stdout_buf;

print "$output" if $verbose;

my @lines = split "\n", $output;

my ($scheduler_state, $controller_state);
my $got_state = 0;
my %tasks;
foreach my $line (@lines) {
    chomp $line;
    next if !$line;
    my ($first, $second, $third);

    if ($line =~ /Scheduler is/) {
        ($first, $second, $scheduler_state) = split " ", $line;
        $got_state = 1;
#        print "$first $second $third $scheduler_state\n";
    } elsif ($line =~ /Controller is/) {
        ($first, $second, $controller_state) = split " ", $line;
#        print "$first $second $third $controller_state\n";
    } elsif ($got_state == 1 and $line =~ /\+|\-/) {
#        print "$line\n";
        my ($task_state, $task, $nrun, $njobs, $ngood, $nfail, $ntime, $cmd) = split " ", $line;
#        print "$task $task_state\n";
        my %this_task = ( name => $task, nrun=> $nrun, njobs => $njobs, ngood => $ngood, nfail => $nfail, ntime => $ntime, cmd => $cmd ); 

        # change '.' in task name to '_' so we have a valid hash key
        $task =~ s/\./\_/g;
        $tasks{$task} =  \%this_task;
    }
}

if ($scheduler_state) {
    print "Pantasks Scheduler $scheduler_state.\n";
    if ($controller_state) {
        print "Pantasks Controller $controller_state.\n";
    } else {
        print STDERR "Controller state not found";
        exit 1;
    }
    print "\n";
} else {
    print STDERR "Scheduler state not found";
    exit 1;
}

my $request_run = $tasks{'pstamp_request_run'};
my $request_fin = $tasks{'request_finish_run'};
my $job_run = $tasks{'pstamp_job_run'};


if ($request_run) {
    print "<b>Parser Status:</b> $request_run->{nrun} running. $request_run->{ngood} parsed successfully.&nbsp; $request_run->{nfail} failed to parse.";
    if ($request_fin) {
        print "  $request_fin->{ngood} Requests finished.";
    } else {
        print "Task request.finish.run not found.\n";
    }
    print "\n";
    print "\n";
    if ($job_run) {
        print "<b>Job Status:</b> &nbsp;&nbsp; $job_run->{nrun} running. &nbsp; $job_run->{ngood} completed successfully. &nbsp; $job_run->{nfail} failed";
        print "\n";
    } else {
        print "Task pstamp.job.run not found.\n";
    }
} else {
    print "Task pstamp.request.run not found.\n";
}


exit 0;
