#!/bin/sh
################################################################################
# This script runs when parallel jobs end.
# Usage: pend
# Imported variables:
#   CONFIG
#   CDATE
#   CDUMP
#   CSTEP
#   LOADL_JOB_NAME
# Configuration variables:
#   PSLOT
#   PCONFIGS
#   MANALhhddd (hh=00,06,12,18;ddd=fnl,gfs)
#   MFCSThhddd (hh=00,06,12,18;ddd=fnl,gfs)
#   CYINC
#   DATATMP
#   NDATE
#   RUNLOG
#   PLOG
#   PSUB
################################################################################
set -ux

PLOG=${PLOG:-$SHDIR/plog}
PSUB=${PSUB:-$SHDIR/psub}
NDATE=${NDATE:-/nwprod/util/exec/ndate}
PCONFIGS=${PCONFIGS:-""}
CCPOST=${CCPOST:-NO}
CYINC=${CYINC:-6}
MANAL=${MANAL:-1}

################################################################################
# Log event

jn=${LOADL_JOB_NAME:-$PSLOT$CDATE$CDUMP$CSTEP}
$PLOG "$RUNLOG" OK "$jn ended"

export CKSH=$(echo $CSTEP|cut -c-4)
export CKND=$(echo $CSTEP|cut -c5-)

################################################################################
# Submit jobs based on script name

nextjobs=""
case $CKSH in

copy)
  nextjobs="$nextjobs $CONFIG,$CDATE,$CDUMP,$CKND"
;;

dump)
  if [[ $CDUMP = fnl ]];then
    nextjobs="$CONFIG,$CDATE,$CDUMP,arch"
  fi
  for config in $PCONFIGS;do
    nextjobs="$nextjobs $config,$CDATE,$CDUMP,prep"
  done
;;

prep)
  nextjobs="$CONFIG,$CDATE,$CDUMP,anal"
;;

anal)
  cycle=$(echo $CDATE|cut -c9-10)
  cdump=$(echo $CDUMP|tr [a-z] [A-Z])
  eval mfcst=\${MFCST$cycle$cdump:-1}
  if [[ $mfcst -ge 1 ]];then
    nextjobs="$CONFIG,$CDATE,$CDUMP,fcst1"
  fi
;;

fcst)
  cycle=$(echo $CDATE|cut -c9-10)
  cdump=$(echo $CDUMP|tr [a-z] [A-Z])
  eval mfcst=\${MFCST$cycle$cdump:-1}
  nknd=${CKND:-1}
  if [[ $CCPOST != YES ]];then
    nextjobs="$CONFIG,$CDATE,$CDUMP,post$CKND"
  fi
  if [[ $nknd -lt $mfcst ]];then
    nknd1=$((nknd+1))
    nextjobs="$nextjobs $CONFIG,$CDATE,$CDUMP,fcst$nknd1"
  fi
;;

post)
  cycle=$(echo $CDATE|cut -c9-10)
  cdump=$(echo $CDUMP|tr [a-z] [A-Z])
  eval mfcst=\${MFCST$cycle$cdump:-1}
  nknd=${CKND:-1}
  if [[ $nknd -eq $mfcst ]];then
    nextjobs="$CONFIG,$CDATE,$CDUMP,vrfy $CONFIG,$CDATE,$CDUMP,arch"
  fi
  if [[ $nknd -eq 1 && $MANAL = 1 && $CDUMP = fnl ]];then
    xdate=$($NDATE +$CYINC $CDATE)
    xcycle=$(echo $xdate|cut -c9-10)
    for xdump in fnl gfs;do
      eval manal=\${MANAL$xcycle$(echo $xdump|tr [a-z] [A-Z]):-1}
      if [[ $manal = 1 ]];then
        nextjobs="$nextjobs $CONFIG,$xdate,$xdump,prep"
      fi
    done
  elif [[ $nknd -eq $mfcst && $MANAL = 0 ]];then
    xdate=$($NDATE +$CYINC $CDATE)
    nextjobs="$nextjobs $CONFIG,$xdate,$CDUMP,fcst1"
  fi
;;

esac

for nextjob in $nextjobs;do
  $PSUB $(echo $nextjob|tr , ' ')
done