#!/bin/bash

runid=ccpl01-02
months=6

# diag_base=$HOME/PRODUCTION/ccpl01/ccpl01_diag
# JOBDESC="ccpl01_base:m pdiag=${diag_base}:12m"

JOBDESC="ccpl01_base:m rtdiag:12m par_mdump:12m"

# Also set ncount below if you want to stop on a given day of the month
# and you are using the old coupler/NCOM based ocean
start=2401
stop=2430

pdiag_first_year=2401
pdiag_chunk_size=60

debug=off

# nemo_from_rest is used to flag starting nemo from rest rather than a restart
nemo_from_rest=off

restart=mc_ccpl00_2400_m12_rs

# Any command line args of the form var=val will be added to the current environment.
# These values will override that of any of the variables that are set above.
# All command line args that are not of the form var=val are ignored.
for arg in "$@"; do
  case $arg in
    *=*) var=`echo $arg|awk -F\= '{printf "%s",$1}' -`
         val=`echo "$arg"|awk '{i=index($0,"=")+1;printf "%s",substr($0,i)}' -`
         [ -n "$var" ] && eval ${var}=\"\$val\" # preserve quoted assignments
         ;;
  esac
done

jobdefs=jobdefs_`date "+%j%H%M%S"$$`
cat >> $jobdefs << end_jobdefs
  uxxx=mc
  runid=$runid
  months=$months
  shortermdir=on
  masterdir=off
  nolist=on
  noprint=on
  keeprs=on

  # degug = on means keep the temporary execution directory after the program finishes
  debug=$debug

  # The version of the coupler that is used
  cancpl_ver=wip/trans-BWGI-in-place-of-HFLI

  # The version of NEMO that is used as well as the location of the NEMO repository
  # nemo_ver=CanCPL_LIM_dev   # use CanCPL_LIM_dev for development/bug fix etc
  nemo_ver=78e7a60c8
  nemo_repo=/users/tor/acrn/rls/src/nemo_cancpl_dev/deploy.git

  # The name of the nemo executable to use (this must be saved on DATAPATH)
  nemo_exec=dev_ccc_cancpl_orca1_lim.exe_78e7a60c-4078e645

  # nemo_config identifies a particular configuration (e.g. CCC_CANCPL_ORCA1_LIM_CMOC)
  nemo_config=CCC_CANCPL_ORCA1_LIM   # NEMO ORCA1 physical ocean with LIM2 ice

  # Turn off OpenMP
  # openmp=off
  # nproc_a=1

  # Use 2 OpenMP threads in the agcm
  # nproc_a=2

  # Use 32 MPI tasks
  #  nnode_a=32
  #  node1='(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)'
  #  node2='(16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)'
  #  node3='(32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80)'

  # Use 1 NEMO tile for entire domain
  # nemo_jpni=1
  # nemo_jpnj=1
  # nemo_jpnij=1
  # nnode_o=1
  # node3='(16,17)'

  # Reset NEMO domain shape
  # nemo_jpni=6
  # nemo_jpnj=8

  # Remove the imprecice compiler option
  # noxlfimp=on

  # Initialize automatic arrays with NaNs
  # noxlfqinitauto=off

  gcmtime=10800

  # This will set or not set the imprecise xlf compiler option for the coupler library only
  # Be sure to set xlfimp = on for production runs
  xlfimp=on

  # Identify the restart file
  # If restart is not defined (ie commented out or define as an empty string)
  # then cccjob will assume you are starting from initial conditions and you
  # must also set samerun and initsp appropriately here
  restart=$restart
  samerun=off
  initsp=off

  # Runoff is not read from a file in NEMO
  nemo_ln_rnf_emp=.true.
  nemo_ln_rnf=.true.
  nemo_runoff_core_monthly=nemo_3.4_orca1_rout_socoeff_month_r1i1p1_1979-2005-mean.nc

  # cpl_rs_abort_if_missing_field = .false. means that the coupler will not abort
  # when it encounters a missing field in the coupler restat file.
  # The default is to abort in this situation.
  # The only valid values for cpl_rs_abort_if_missing_field are .true. or .false.
  cpl_rs_abort_if_missing_field=.false.

  # Is a bulk formulation used in the coupler to define fields sent to NEMO
  bulk_in_cpl=.false.

  # couple_serial = .true. means couple in serial mode (the agcm runs then the ocean runs)
  # This should never be set unless debugging requires serial mode
  # The only valid values for couple_serial are .true. or .false. (default .false.)
  couple_serial=.true.

  # Generate coupler run time diagnostics
  cpl_rtd=on

  # When cpl_new_rtd is on any rtd file found in the coupler restart
  # will be ignored and a new rtd file will be started
  cpl_new_rtd=on

  # Coupling related parameters
  coupled=on
  ocnmod="00002"
  icemod="00001"
  # Use a 1 day coupling frequency
  # ksteps=96
  # isbeg=96
  # israd=96
  # Use a 3 hour coupling frequency
  ksteps=12
  isbeg=12
  israd=12
  # Use a 1 hour coupling frequency
  # ksteps=4
  # isbeg=4
  # israd=4

  float1=off

  # Save coupler history files to DATAPATH
  save_cplhist=on
  save_cplhist_tavg=off

  # nemo_from_rest is used to flag starting nemo from rest rather than a restart
  # If nemo_from_rest = on then nemo_restart must be undefined
  # If nemo_from_rest = on then nemo_namelist and nemo_namelist_ice must be defined
  nemo_from_rest=$nemo_from_rest

  # The name of the nemo restart tarball
  # nemo_restart='mc_oda-o1c-cv2_07491231_restart.tar'

  # If nemo_rebuild_rsin = on then the NEMO restart will be
  # used to initialize fields that are sent from the coupler to the agcm on the first
  # coupling interval. This restart will be rebuilt on the global ORCA grid prior to model
  # execution and then read by the coupler to extract the relevant fields.
  nemo_rebuild_rsin=off

  # Save NEMO history files to DATAPATH
  nemo_save_hist=off

  # Dump NEMO history files to cfs
  nemo_dump_hist=off

  # Optionally delete NEMO history files from DATAPATH
  nemo_del_hist=off

  # Save NEMO restart files to DATAPATH
  nemo_save_rs=on

  # Dump NEMO restart archives to cfs
  nemo_dump_rs=off

  # Delete the previous nemo restart tar archive from DATAPATH.
  nemo_del_rs=off

  # Generate nemo run time diagnostics
  nemo_rtd=on

  # When nemo_new_rtd is on any rtd file found in the NEMO restart
  # will be ignored and a new rtd file will be started
  nemo_new_rtd=off

  # Optionally dump/delete non-NEMO files in nemo_postlude
  # nemo_other_hist_suffix_list='gs ss cplhist.nc'
  # nemo_other_rs_suffix_list='rs cplrs.nc cpl_stats cplhist.nc'

  # nemo_rtdiag_start_year is used in the nemo run time diagnostic file name
  nemo_rtdiag_start_year=2351

  # NEMO time step in seconds
  nemo_rn_rdt=3600

  # remove (nemo_nn_closea = 0) or keep (nemo_nn_closea = 1) closed seas and lakes (ORCA)
  nemo_nn_closea=0

  # nemo_steps_in_job is the total number of NEMO time steps to run
  # This number is determined internally and so is not normally set here
  # but it may be used for debugging (caveat lector)
  # nemo commonly uses a 1 hour time step
  # nemo_steps_in_job=6
  # nemo_steps_in_job=30

  # kfinal is not normally set directly by the user
  # kfinal=81888492
  #  6 hours from kount = 85848000 implies kfinal = 85848024  (assuming delt=900)
  # 30 hours from kount = 85848000 implies kfinal = 85848120  (assuming delt=900)
  # kfinal=85848024
  # kfinal=85848120

  # output the initial state (nemo_nn_istate = 1) or not (nemo_nn_istate = 0)
  # nemo_nn_istate=1

  # time steps between creation of NEMO restart files (modulo referenced to 1)
  # nemo_nn_stock=1

  # The number of NEMO time steps between calls to sbc and LIM2 (or CICE)
  nemo_nn_fsbc=1

  # nemo_nn_ice identifies the ice model
  #   nemo_nn_ice = 0 mean no sea ice
  #   nemo_nn_ice = 2 mean LIM2
  #   nemo_nn_ice = 4 mean CICE
  nemo_nn_ice=2

  # nemo_ln_ctl toggles printing of diagnostic messages from NEMO
  # nemo_ln_ctl must be either .false. or .true. (ie a fortran logical constant)
  # since it is read from a fortran namelist
  nemo_ln_ctl=.true.

  # nemo_nn_msh  determines if NEMO will create (=1) a mesh file or not (=0)
  nemo_nn_msh=1

  # CICE time step in seconds
  # cice_dt=900

  # The number of CICE time steps for each call to CICE_Run
  # cice_npt=24

  # The value of "year_init" in the CICE namelist (0)
  # cice_year_init=0

  # The value of "runtype" in the CICE namelist (initial or continue)
  # cice_runtype=initial

  # The value of "ice_ic" in the CICE namelist (none, default, ice ic file name)
  # cice_ice_ic=none

  # The value of "restart" in the CICE namelist (.true. or .false.)
  # cice_restart=.false.

  # Change ncount if the job should stop before the end of the month
  # ncount is the day of the month on which the ocean will stop when using CanOM4
  # ncount="00002"

  # User supplied ocean source directory when using CanOM4
  # user_source=/users/tor/acrn/rls/src/coupler/run/canesm4.2_ocn_mods

  # AGCM run time diags related parameters
  year_rtdiag_start=2401
  rtd_diag_deck=rtdiag72.dk

  # When par_mdump_with_del = on then the files that are dumped by par_mdump
  # will also be deleted from DATAPATH after they are put on cfs
  par_mdump_with_del=on

  # Files to be dumped and deleted by mdump and mdelete
  mdump_suffix_list='gs ss cplhist.nc'
  mdelete_suffix_list='gs ss cplhist.nc'
  bemach=hadar

  pdiag_dump_hist=off
  pdiag_dump_diag=off
  pdiag_rtd_plot_freq=2
  pdiag_first_year=$pdiag_first_year
  pdiag_with_rtd=on
  pdiag_with_dd=off
  pdiag_with_dp=off
  pdiag_with_gz=off
  pdiag_with_cp=off
  pdiag_with_cplrs=on
  pdiag_with_cplhist=on
  pdiag_delete_diag=on
  pdiag_with_time_series=on
  pdiag_with_pool=on
  psdelete_leave_last_pool=on
  pdiag_transfer_time_series=off
  pdiag_chunk_size=$pdiag_chunk_size
  pdiag_first_chunk_size=$pdiag_chunk_size
  pdiag_front_end=hadar
  pdiag_besc=on
  pdiag_gptime=1800
  pdiag_stime=1800
  diag2ts_delete_time_series=on
  model_version=gcm18

end_jobdefs

start_time=(${start//:/ })
stop_time=(${stop//:/ })
printf -v date1 "%3.3dm%2.2d" ${start_time[0]:-1} ${start_time[1]:-1}
printf -v date2 "%3.3dm%2.2d" ${stop_time[0]:-1} ${stop_time[1]:-12}
if [[ ${#start_time[@]} -gt 2 ]]; then
  [ -n "${start_time[2]}" ] && printf -v d1 "d%2.2d" ${start_time[2]} && date1+="$d1"
fi
if [[ ${#stop_time[@]} -gt 2 ]]; then
  [ -n  "${stop_time[2]}" ] && printf -v d2 "d%2.2d" ${stop_time[2]}  && date2+="$d2"
fi
range="${date1}_${date2}"

fout="${runid}_${range}_job"

# Create the job
cccjob --out=$fout --job="$JOBDESC" --start=$start --stop=$stop --restart=$restart $jobdefs

rm -f $jobdefs

