#! /bin/sh

# JHMON_HYCOM_INIT1 - this job runs the hycom init for coupled forecast
#
# Runs in parallel with:
#   JHMON_NPS_IC
#   JHMON_NPS_BC
#   JHMON_HYCOM_INIT_2
#
# Dependencies:
#   JHMON_LAUNCH
#
# Next Job:   JHMON_FORECAST
#

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 COMINgfs=${COMINgfs:-$(compath.py gfs/${gfs_ver})}
export COMINgdas=${COMINgdas:-$(compath.py gfs/${gfs_ver})}
export COMINarch=${COMINarch:-$(compath.py gfs/${gfs_ver})/syndat}
export COMINrtofs=${COMINrtofs:-$(compath.py rtofs/${rtofs_ver})}
export COMINmsg=${COMINmsg:-$(compath.py hafs/${hafs_ver}/inphfsb)}

# HMON areas:
priorymdh=$( $NDATE -6 "$PDY$cyc" )
pre_YMD=`echo $priorymdh |cut -c1-8`
pre_H=`echo $priorymdh |cut -c9-10`
export HISTDATA=${HISTDATA:-$(compath.py -o $RUN/${hmon_ver})/$RUN.$pre_YMD/$pre_H}
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}}

# Point to stormX.conf generated by launcher job:
#export CONFhmon=$COMIN/storm$storm_num.conf

# 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_init1.py."
$EXhmon/exhmon_hycominit1.py ${TOTAL_TASKS:?}
export err=$?; err_chk
postmsg "$jlogfile" "exhmon_hycom_init1.py ended normally."