# -*- Perl -*-

#
# Based on /usr/lpp/LoadL/full/samples/lldata_access/wall_clock_time.c
#
# Requires the jobstep to be in the form <host>.<domain>.<jobno>.<stepno>
#

use IBM::LoadLeveler;
use Getopt::Std;
use Sys::Hostname;

@StepState=( "I", "P", "ST", "R",
    "CP", "XP", "RP",
    "VP", "C", "X", "RM",
    "V", "CA", "NR", "TX",
    "?", "SX", "H", "D",
    "NQ", "E", "EP",
    "MP");

getopts("j:");
@steplist = ($opt_j,NULL);

# Format for llq style output
format STDOUT_TOP =

                                             WallClock Remaining
   Hostname             StepId                Hard        Soft
--------------- ------------------------- ------------ ------------
.

format STDOUT =
@<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<< @<<<<<<<<<<<
$mach_name, $id, $tremain_h, $tremain_s
.

$queryObject = ll_query(JOBS);
$rc = ll_set_request($queryObject, QUERY_STEPID, \@steplist, ALL_DATA);
if ( $rc ) {
  print "ll_set_request() - QUERY_STEPID, rc = $rc\n";
  exit(1);
}

# Try and work out our domain name

$host=hostname();
my($fqdn)=gethostbyname($host);
$fqdn=~/$host\.(.*)/;
$domain= $1;

$job = ll_get_objs($queryObject, LL_CM, NULL, $obj_count, $err_code);
if ( $job ) {

  $step = ll_get_data($job, LL_JobGetFirstStep);
  if ( $step ) {

    $id = ll_get_data($step, LL_StepID);

    # strip domain name from step name for ease of reading

    $tmp=$id;
    $id=$1 . $2 if $tmp=~/(.*).$domain(.*)/;

    $wcl_h = ll_get_data($step, LL_StepWallClockLimitHard);
    $wcl_s = ll_get_data($step, LL_StepWallClockLimitSoft);

    $state = ll_get_data($step, LL_StepState);
    $st = $StepState[$state];

    if ( $state == STATE_RUNNING or $state == STATE_PREEMPTED
        or $state == STATE_RESUME_PENDING 
        or $state == STATE_PREEMPT_PENDING ) {

      $machine = ll_get_data($step, LL_StepGetFirstMachine);
      if ( $machine ) {
        $mach_name = ll_get_data($machine, LL_MachineName);
      } else {
        print "Error - unable to get machine name\n";
      }

    } else {
        print "Error - Jobstep not in appropiate state\n";
    }

  } else {
     print "Error - no Jobstep information\n";
  }

}

if ( $mach_name ) {

  ll_reset_request($queryObject);
  $rc = ll_set_request($queryObject, QUERY_STEPID, \@steplist, ALL_DATA);
  if ( $rc ) {
    print "ll_set_request() - QUERY_STEPID, rc = $rc\n";
    exit(1);
  }

  $job = ll_get_objs($queryObject, LL_STARTD, $mach_name, $obj_count, $err_code);
  if ( $err_code > 0 ) {
    print "Error - cannot connect to startd node, rc = $err_code\n";
    exit(1);
  }

  if ( $job ) {
    $step = ll_get_data($job, LL_JobGetFirstStep);
    if ( $step ) {
      $tmp=$mach_name;
      $mach_name=$1 . $2 if $tmp=~/(.*).$domain(.*)/;
      $wused = ll_get_data($step, LL_StepWallClockUsed);
      $sdate = ll_get_data($step, LL_StepStartDate);
      $tremain_h = $wcl_h - $wused;
      $tremain_s = $wcl_s - $wused;
      write;
    }
  }

}
