#!/bin/bash
#     keyword :: canesm_rtd_coupler
# description :: Coupler run-time diagnostics
set -a
. betapath2  # sets path for new package (required until old package is retired)

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

 runid="runid"; year="yyyy"; year_rtdiag_start="yyyy"; month_rtdiag_start="mm"; crawork="crawork";
 coupler_rtd_mons="01"

 # rtd executables
 coupler_rtd_exe=cpl_rtd_v01299fc_ppp.exe

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

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

 noprint=on
 nextjob=on
 debug=off
 keep_old_rtdiag=off

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

# NCS, Feb 2018
# We are reverting to the AGCM RTD approach, since this is being run in the
# coupled model, and it is easiest to be consistent across models
# What this means is that we are going to run RTD in one year chunks. We
# are going to make the hard assumption that the coupled model was run
# in monthly chunks, with monthly output. Hence, this RTD job will loop
# over the 12 months for the current year, computing the RTD for each
# month progressively.
# We are also going to use the rtdiag_start_year paradigm. That is, we are
# going to save files with names including the dates, which for the current
# segment will be from rtdiag_start_year to year.

# Add job specific functions, definitions etc
  : ; . local_defs

# first and last months
  mon1=`echo ${month_rtdiag_start:-1} | awk '{printf "%02d",$1}'`
  monl=`expr $mon1 + 11`
  if [ $monl -gt 12 ] ; then
    mon2=`echo $monl | awk '{printf "%02d",$1-12}'`
    yr1=`echo $year | awk '{printf "%03s", $1-1}'`;
  else
    mon2=`echo $monl | awk '{printf "%02d",$1}'`
    yr1=$year
  fi
  nmon=`expr $monl - $mon1 + 1`

# Timing: figure out previous year, and previous RTD file
  keep_old_rtdiag_number=${keep_old_rtdiag_number:=3}
  echo keep_old_rtdiag_number=$keep_old_rtdiag_number

  yearm1=`echo $year | awk '{printf "%03s", $1 - 1}'`
  yearmo=`echo $year $keep_old_rtdiag_number | awk '{printf "%03s", $1 - $2}'`

  if [ $mon1 -eq 1 ] ; then
    # current year rtd file names
    coupler_rtdfile=sc_${runid}_${year_rtdiag_start}_${year}_coupler_rtd.nc

    # previous year rtd file names
    coupler_rtdfile1="sc_${runid}_${year_rtdiag_start}_${yearm1}_coupler_rtd.nc"

    # older rtd file to be deleted (depends on keep_old_rtdiag_number)
    coupler_rtdfileo="sc_${runid}_${year_rtdiag_start}_${yearmo}_coupler_rtd.nc"
  else
    # current year rtd file names
    coupler_rtdfile=sc_${runid}_${year_rtdiag_start}${mon1}_${year}${mon2}_coupler_rtd.nc

    # previous year rtd file names
    coupler_rtdfile1="sc_${runid}_${year_rtdiag_start}${mon1}_${yearm1}${mon2}_coupler_rtd.nc"

    # older rtd file to be deleted (depends on keep_old_rtdiag_number)
    coupler_rtdfileo="sc_${runid}_${year_rtdiag_start}${mon1}_${yearmo}${mon2}_coupler_rtd.nc"
  fi

# Access old RTD files from last year. Note, if these files exist, the RTD programs
# below will automatically append to them.

  if [ $yr1 -gt ${year_rtdiag_start} ] ; then
      access coupler_rtd_old.nc $coupler_rtdfile1 nocp=off ; cp coupler_rtd_old.nc coupler_rtd.nc ; chmod +w coupler_rtd.nc
  fi

# Get the RTD executables
  # Access the physical rtd executable

  [ -z "$coupler_rtd_exe" ] && bail "physical_rtd_exe is not defined."
  [ -s "$coupler_rtd_exe" ] || access $coupler_rtd_exe $coupler_rtd_exe

  ######## Compute the rt diagnostics #######

    # Invoke the coupler run time diagnostics
  echo "Doing  Coupler RTD for files with months ${coupler_rtd_mons}"

  # Month loop
  for mon in $coupler_rtd_mons ; do
      echo $mon
      if [ $mon1 -eq 1 ] ; then
        yearm=$year
      else
        if [ $mon -ge $mon1 ] ; then
          yearm=`expr $year - 1`
        else
          yearm=$year
        fi
      fi
                   # Coupler run time diagnostics

      # Attempt to access the "coupler" history files
      rtd_hist1="mc_${runid}_${year}_m${mon}_cplhist.nc"
      access cplhist $rtd_hist1 na #|| bail "Coupler rdt cannot access $rtd_hist1"

      # Create run time diagnostics for coupler variables
      $coupler_rtd_exe ${yearm} ${mon}

      # Clean up
      release cplhist
   done # month loop end

#   Modify attributes
    [ -s coupler_rtd.nc ] && ncatted -a RTD_version,global,o,c,"${coupler_rtd_exe}\n" coupler_rtd.nc

#   Move RTD files for staging back to Victoria
    rtd_staging coupler_rtd.nc $coupler_rtdfile

  # Save new RTD files.
    save coupler_rtd.nc $coupler_rtdfile

# ************************************ delete older rtd files
    if [ "$keep_old_rtdiag" != "on" ] ; then
      release old
      access  old $coupler_rtdfileo na
      delete  old na
    fi
end_of_script

cat >local_defs << 'end_local_defs'
  stamp=`date "+%j%H%M%S"$$`

  # this_host will simply be the output from uname
  this_host=`uname -n|awk -F\. '{print \$1}' -`

  # this_mach will be a known alias (or possibly the actual machine name)
  this_mach=$this_host
  ROUTE_SSH=''
  case $this_mach in
             xc1*) this_mach=hare;   ROUTE_SSH='ssh hare'  ;;
             xc2*) this_mach=brooks; ROUTE_SSH='ssh brooks'  ;;
             xc3*) this_mach=banting; ROUTE_SSH='ssh banting'  ;;
             xc4*) this_mach=daley; ROUTE_SSH='ssh daley'  ;;
      eccc1-ppp1*) this_mach=ppp1;   ROUTE_SSH='ssh ppp1'  ;;
      eccc1-ppp2*) this_mach=ppp2;   ROUTE_SSH='ssh ppp2'  ;;
      hpcr3*|cs3*|ppp3*|eccc*-ppp3*) this_mach=ppp3;   ROUTE_SSH='ssh ppp3'  ;;
      hpcr4*|cs4*|ppp4*|eccc*-ppp4*) this_mach=ppp4;   ROUTE_SSH='ssh ppp4'  ;;
     ib3*) this_mach=pollux; ROUTE_SSH='ssh pollux' ;;
   joule*) this_mach=joule;  ROUTE_SSH='ssh joule'  ;;
  esac

 rtd_staging() {
    # Copy a single rtd file to a local staging directory
    # Usage: rtd_staging local_rtd_file remote_rtd_file
    [ -z "$1" ] && bail "rtd_staging requires a file name as the first arg."
    [ -z "$2" ] && bail "rtd_staging requires a file name as the second arg."
    [ -e $1 ] || bail "rtd_staging: File --> $1 <-- is missing."

    # Do not abort if the copy fails

    # Identify the staging directory

    HOSTID=`hostname | cut -d'.' -f1 `
    case ${HOSTID} in
      cs1*|ppp1*|eccc*-ppp1*) # ppp1
            rtd_staging_dir=/space/hall1/sitestore/eccc/crd/rtdfiles_coupler
            ;;
      cs2*|ppp2*|eccc*-ppp2*) # ppp2
            rtd_staging_dir=/space/hall2/sitestore/eccc/crd/rtdfiles_coupler
            ;;
      hpcr3*|cs3*|ppp3*|eccc*-ppp3*) # ppp3
            rtd_staging_dir=/space/hall3/sitestore/eccc/crd/rtdfiles_coupler
            ;;
      hpcr4*|cs4*|ppp4*|eccc*-ppp4*) # ppp4
            rtd_staging_dir=/space/hall4/sitestore/eccc/crd/rtdfiles_coupler
            ;;
        *) rtd_staging_dir=/space/hall1/sitestore/eccc/crd/rtdfiles_coupler
            ;;
    esac

    echo "staging" $rtd_staging_dir
    [ -z $rtd_staging_dir ] && bail "rtd_staging_dir not defined"
    cp $1 $rtd_staging_dir/$2
  }

  # bail is a simple error exit routine
  error_out="${JHOME:-$HOME}/.queue/error_coupler_processing_${runid}_${this_host}_$stamp"
  [ -z "$error_out" ] || rm -f $error_out
  bail_prefix="COUPLER RTD"
  bail(){
    echo `date`" $this_host $runid --- ${bail_prefix}: $*"
    echo `date`" $this_host $runid --- ${bail_prefix}: $*" >>$error_out
    [ -n "$model" ] && echo `date`" $this_host $runid --- ${bail_prefix}: $*" >>haltit
    exit 1
  }

end_local_defs

. endjcl.cdk
#end_of_job
