#!/bin/bash
#     keyword :: canesm_post
# description :: Post-processing job (transfer, rebuild, rtds, diagnostics, etc.)
set -a
. betapath2  # sets path for new package (required until old package is retired)

#  * ........................... Parmsub Parameters ............................

 runid="runid"; year="yyyy"; crawork="crawork";

 username="username"; user="USER"; nqsprfx=""; nqsext="_${runid}_${year}";
 lopgm="lopgm"; stime="3600"; memory1="1gb";

#  * ............................ Condef Parameters ............................

 noprint=on
 nextjob=on

#  * ............................. Deck Definition .............................
jobname=post; time=$stime ; memory=$memory1
.   comjcl.cdk
cat > Execute_Script <<'end_of_script'

# input directory with model and diagnostic base/makejob files
cd $WRK_DIR

finp=make_diag_job_${runid}
fout=make_diag_job_${runid}_${year}
diagjob_sfx=diagjob_`echo ${CMCFEDEST} | cut -f2 -d'-'`_${DIAGJOB_SFX}

# modify some parameters in make_diag_job_${runid}
cat $finp | sed \
 -e "s/^start\=[0-9]\+/start\=$year/" \
 -e "s/^stop\=[0-9]\+/stop\=$year/" \
 -e "s/crawork\=.\+/crawork\=${runid}_${diagjob_sfx}/" \
> $fout

# create diag string to be run on front end
chmod +x $fout
./$fout

# the resulting diag job is saved in
fdiag="${runid}_${year}m01_${year}m12_diag_job"

# checks if the job is being updated
ntrymax=10
for n in `seq 1 1 $ntrymax` ; do
  if [ -f "$HOME/.queue/.crawork/.${runid}_${diagjob_sfx}_string_updtng" ] ; then
    sleep 5
  else
    break
  fi
  if [ $n -eq $ntrymax ] ; then
    abort='abort'
    echo "ERROR: there is a lock file in the crawork directory:"
    echo "ERROR:  $HOME/.queue/.crawork/.${runid}_${diagjob_sfx}_string_updtng"
    echo "ERROR: Remove it before resubmitting the job."
    exit 1
  fi
done
# submit diag job to FE
if [ -s "$HOME/.queue/.crawork/${runid}_${diagjob_sfx}_string" ] ; then
  cat $fdiag >> $HOME/.queue/.crawork/${runid}_${diagjob_sfx}_string
else
  dest=`echo $CMCFEDEST | cut -f2 -d'-'`
  rsub mdest=$dest $fdiag
fi

# move jobs to post_jobs subdirectory
mv $fout $fdiag $WRK_DIR/post_jobs/

end_of_script

. endjcl.cdk
#end_of_job
