#!/bin/sh

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

export cycle=${cycle:-t${cyc:?}z}
export storm_num=${storm_num:-1}
export stormlabel=${stormlabel:-storm$storm_num}
export hafs_ver=${hafs_ver:?}
export NET=${NET:?}
export RUN=${RUN:?}
export RUN_ENVIR=${RUN_ENVIR:?}

export SENDCOM=${SENDCOM:-YES}
export SENDDBN=${SENDDBN:-NO}
export SENDECF=${SENDECF:-NO}
export EMAIL_SDM=${EMAIL_SDM:-NO}
export SCRUBDATA=${SCRUBDATA:-YES}
# HAFS workflow jobs use shared working dir, and the CLEANUP or SCRUB job will clean up WORKhafs
#export KEEPDATA=${KEEPDATA:-YES}
export KEEPDATA=YES

export HOMEhafs=${HOMEhafs:-${OPSROOT:?}/hafs.${hafs_ver:?}}
export USHhafs=$HOMEhafs/ush
export EXEChafs=$HOMEhafs/exec
export PARMhafs=$HOMEhafs/parm
export FIXhafs=$HOMEhafs/fix

export WORKhafs=${WORKhafs:-${DATAROOT:?}/${RUN:?}${storm_num:?}_${cyc:?}_${envir:?}_${hafs_ver:?}}

if [ "${RUN_ENVIR^^}" != "NCO" ]; then
  # Detect platform and load modules if not run by NCO
  source ${USHhafs}/hafs_pre_job.sh.inc
  export machine=${WHERE_AM_I:-wcoss2}
  module list
else
  # Run by NCO on WCOSS2
  export machine=${WHERE_AM_I:-wcoss2}
  # Prepend $USHhafs to python package search path
  export PYTHONPATH=$USHhafs${PYTHONPATH:+:$PYTHONPATH}
  # Initialize PDY
# setpdy.sh # only needed for the launch job
  # Get PDY
  source ${WORKhafs}/PDY
fi

source ${USHhafs}/hafs_runcmd.sh.inc

env

export COMhafs=${COMhafs:-$(compath.py ${envir}/${NET}/${hafs_ver})/${RUN}.${PDY}/${cyc}}
export CONFhafs=$COMhafs/$stormlabel.conf
export HOLDVARS=${HOLDVARS:-$COMhafs/$stormlabel.holdvars.txt}

source ${HOLDVARS}

export POST_CLEANUP=${POST_CLEANUP:-NO}

export DATA=${WORKhafs}/unpost

if [ "${SCRUBDATA:-YES}" = "YES" ]; then
  rm -rf $DATA
fi
mkdir -p $DATA
cd $DATA

# Execute ex-script
${HOMEhafs}/scripts/exhafs_unpost.sh
export err=$?; err_chk

# Cleanup DATA dir
cd ${WORKhafs}
if [ "${KEEPDATA:-YES}" != "YES" ]; then
  rm -rf $DATA
fi

date