#!/bin/sh

###########################################
# Set up environment for cpci
###########################################
set -xa
export PS4='$SECONDS + ' 
date

###############################
# Specify NET and RUN name
###############################
export DATA=${DATA:-${DATAROOT}/${jobid}}    

if [ -d $DATA ]; then    
  rm -rf $DATA    
fi    
mkdir -p $DATA    
cd $DATA 

export NET=${NET:-cpci}
export RUN=${RUN:?'variable RUN has to be set in ecf file'}
####################################
# Determine Job Output Name on System
####################################
export pgmout="OUTPUT.${jobid}"
export cycle=${cycle:-t${cyc}z} 

############################################
#SENDCOM=YES       copy output file to /com
#SENDDBN=YES       alert data out to TOC
#SENDECF=YES       send message back to ecFlow
############################################
export SENDCOM=${SENDCOM:-NO}
export SENDDBN=${SENDDBN:-NO}
export SENDECF=${SENDECF:-NO}

###################################
# Set up restart variable RERUN (default = NO)
# (YES means start from the beginning,
# NO means pick up where forecast left off, if able to)
###################################
export FIXcpci=${FIXcpci:-$HOMEcpci/fix}
export USHcpci=${USHcpci:-$HOMEcpci/ush}

# Run setpdy and initialize PDY variables
setpdy.sh
. ./PDY

if [ "$RUN" == 'gdas' ]; then
  export COMIN=${COMIN:-$(compath.py ${envir}/gfs/${gfs_ver})/gdas.${PDY}}
  export COMINnawips=${COMINnawips:-$(compath.py ${envir}/gfs/${gfs_ver})/gdas.${PDY}/${cyc}/atmos/gempak}
fi
if [ "$RUN" == 'gefs' ]; then
  export COMIN=${COMIN:-$(compath.py ${envir}/gefs/${gefs_ver})/gfs.${PDY}}
  export COMINnawips=${COMINnawips:-$(compath.py ${envir}/gefs/${gefs_ver})/gefs.${PDY}/${cyc}/atmos/gempak}
fi
if [ "$RUN" == 'gefs_boxw' ]; then
  export COMIN=${COMIN:-$(compath.py ${envir}/gefs/${gefs_ver})}
fi
if [ "$RUN" == 'gfs' ]; then
  export COMIN=${COMIN:-$(compath.py ${envir}/gfs/${gfs_ver})/gfs.${PDY}}
  export COMINnawips=${COMINnawips:-$(compath.py  ${envir}/gfs/${gfs_ver})/gfs.${PDY}/${cyc}/atmos/gempak}
fi
if [ "$RUN" == 'gfs_skewt' ]; then
  export COMIN=${COMIN:-$(compath.py ${envir}/gfs/${gfs_ver})}
fi

export COMOUT=${COMOUT:-$(compath.py -o $NET/${cpci_ver}/$NET.${PDY})/${RUN}/${cyc}}
export TAROUT=`dirname ${COMOUT}`

if [ ! -d $COMOUT ]    
then    
 mkdir -p $COMOUT    
fi 
env

###################################################
# Execute the Script
#
${HOMEcpci}/scripts/excpci_${RUN}.sh
#
###################################################

pwd

cat ${pgmout}
cat errfile

msg="JOB ${model} FOR PROJECT=${RUN} HAS COMPLETED NORMALLY."
postmsg "$msg"

date
#
if [ "$KEEPDATA" != 'YES' ]; then
   rm -rf $DATA
fi