#! /bin/ksh
#
# Script name:         exdgex_pmgr.sh.sms
#
#  This script monitors the progress of the DGEX fcst job
# and releases the post jobs.
#
# Script history
#
#  2006-04-24 : Eric Rogers modified original for WRF-NMM DGEX
#

set -x

export PS4='$SECONDS + '
export tmmark=tm00

# Unlike Eta version of DGEX, NMM DGEX prelim step model processes the 78-h NAM as
# if it were a 00-h initial condition, so DGEX post processes hours 3-114 (=81-192 h DGEX
# forecast hours) After DGEX post runs, a special version of overdate is run to  
# 1) backdate the start time in each GRIB file by 78-h and 2) increase the forecast hour by 78 to
# mimic the output of the Eta-based DGEX.

hour=003

if [ -e posthours ]; then
   rm -f posthours
fi

while [ $hour -lt 115 ]; 
do
    echo $hour >>posthours
    let "hour=hour+3"
    if [ $hour -lt 10 ]
    then
      hour=00${hour}
    fi
    if [ $hour -ge 10 -a $hour -lt 100 ]
    then
      hour=0${hour}
    fi
done
postjobs=`cat posthours`

#
# Wait for all fcst hours to finish 
#
icnt=1
while [ $icnt -lt 1500 ]
do
  for fhr in $postjobs
  do
    if [ -s $DATA/fcstdone.${fhr}h_00m_00.00s ]
    then
       sms_fhr=`expr $fhr`
       if [ $sms_fhr -lt 10 ]; then sms_fhr=0$sms_fhr; fi
       $SMSBIN/setev release_post${sms_fhr}
      # Remove current fhr from list
      postjobs=`echo $postjobs | sed s/${fhr}//g`
    fi
  done
  
  result_check=`echo $postjobs | wc -w`
  if [ $result_check -eq 0 ]
  then
     break
  fi

  sleep 10
  icnt=$((icnt + 1))
# if [ $icnt -ge 540 ]
# then
#   msg="ABORTING after 1.5 hours of waiting for DGEX FCST hours $postjobs."
#   err_exit $msg
# fi

done

echo Exiting $0

exit
