#! /bin/sh

# JHMON_HYCOM_POST - Converts the HYCOM output files to grid GRIB
# files.  If this job fails, and you resubmit it, it will rerunn everything.  
#
# Runs in parallel with:
#   JHMON_FORECAST
#   JHMON_POST_1
#   JHMON_POST_2
#
# Next jobs:
#   JHMON_TRACKER(after all of its other dependencies are met)

date
export PS4='+ $SECONDS + '
set -xu

####################################
# Set default values if not yet set
# values from ecFlow or modules will override these
####################################
export DATA=${DATA:-${DATAROOT:?}/hmon${storm_num:?}_${cyc:?}_${envir:?}}
export cycle=${cycle:-t${cyc}z}
export jlogfile=${DATA}/jlogfile

####################################
# Initialize work area and cd there
####################################
mkdir -p $DATA
cd $DATA

####################################
# Variables for logging & DBnet
####################################
export NET=hmon RUN=hmon

####################################
# Set threading defaults
####################################
export OMP_NUM_THREADS=1
export OMP_STACKSIZE=128M
export MKL_NUM_THREADS=1

####################################
# Set HMON-specific vars
####################################
# Top of HMON installation tree:
export HOMEhmon=${HOMEhmon:-${PACKAGEROOT:?}/hmon.${hmon_ver:?}}
export USHhmon=$HOMEhmon/ush
export EXhmon=$HOMEhmon/scripts
export PARMhmon=$HOMEhmon/parm
export FIXhmon=$HOMEhmon/fix
export EXEChmon=$HOMEhmon/exec
export WORKhmon=$DATA

# Get PDY
. ./PDY

# set up cycle
export CYCLE=${PDY}${cyc}

# Upstream and downstream areas:
export stormlabel=${stormlabel:-storm$storm_num}
export COMINarch=${COMINarch:-$(compath.py gfs/${gfs_ver})/syndat}

# JY not sure if the COMINmsg is actually used, define it anyway
export COMINmsg=${COMINmsg:-$(compath.py hwrf/${hwrf_ver}/inphmon)}

# HMON areas:
priorymdh=$( $NDATE -6 "$PDY$cyc" )
export HISTDATA=${HISTDATA:-$(compath.py $NET/${hmon_ver})/$RUN.$priorymdh}
export COMIN=${COMIN:-$(compath.py $NET/${hmon_ver})/$RUN.$PDY$cyc}
export COMOUT=${COMOUT:-$(compath.py -o $NET/${hmon_ver})/$RUN.$PDY$cyc}
export COM=${COM:-${COMOUT}}

# Prepend $USHhmon to python package search path:
export PYTHONPATH=$USHhmon${PYTHONPATH:+:$PYTHONPATH}

# Make sure all mandatory variables are set: cyc, storm_num
set -u +x
echo "Checking for mandatory variables:"
echo "cyc=$cyc storm_num=$storm_num"
set +u -x
env
####################################
# Set/check job-specific vars if any
####################################

####################################
# Pass control to ex-script
####################################


postmsg "$jlogfile" "Starting exhmon_hycom_post.py."
$EXhmon/exhmon_hycom_post.py ${TOTAL_TASKS:?}
export err=$?; err_chk
postmsg "$jlogfile" "exhmon_hycom_post.py ended normally."