#!/bin/bash
set -e
#
# save restart files script
#
#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
canesm_cfg_file=canesm.cfg	# config file
#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#

# Source the config file
. ${canesm_cfg_file}

# parent information is taken from canesm.cfg file but can be overwritten below

runid_in_a=${parent_runid}	# Parent runid to be used as AGCM restart
date_in_a=${parent_branch_time}	# Restart date in the parent run for AGCM

runid_in_c=${parent_runid}	# Parent runid to be used as Coupler/NEMO restart
date_in_c=${parent_branch_time}	# Restart date in the parent run for Coupler/NEMO

# optional local database to access files from another run on the same machine:
# edit $USER of the input runid, if it comes from a different user.
DATAPATH_DB_OPT=$RUNPATH_ROOT/users/$USER/$runid_in_a/datapath_local.db

Usage='Usage:

  save_restart_files [-p] [-d] MODEL_JOB

  If -p is specified, save PHYS_PARM from the local run directory in
  RUNPATH. Otherwise, use the file from the parent run, if exists.

  If -d is specified, save INLINE_DIAG_NL from the local run directory
  in RUNPATH. Otherwise, use the file from the parent run, if exists.
'
use_local_phys_parm=0
use_local_inline_diag_nl=0
while [[ "$#" -gt 0 ]]; do
  case $1 in
    -p) use_local_phys_parm=1
      ;;
    -d) use_local_inline_diag_nl=1
      ;;
    *) MODEL_JOB=$1
      ;;
  esac
  shift
done
# check that the model job is provided and exists
if [ -z "$MODEL_JOB" -o ! -s "$MODEL_JOB" ] ; then
  echo "$Usage"
  exit 1
fi
# check that $runid=$runid_env
if [ "$runid" != "$runid_env" ]; then
  echo "ERROR: runid=$runid is not the same as runid_env=$runid_env."
  echo "Make sure to source env_setup_file."
  exit 1
fi
echo use_local_phys_parm=$use_local_phys_parm
echo use_local_inline_diag_nl=$use_local_inline_diag_nl
echo MODEL_JOB=$MODEL_JOB

# derive start_year and start_month
start_date=(${start_time//:/ })
start_year=${start_date[0]:-1}
start_month=${start_date[1]:-1}

# derive date_out from start_year/start_month
if [ $start_month -eq 1 ] ; then
  year_out=`expr $start_year - 1`
  month_out=12
else
  year_out=$start_year
  month_out=`echo $start_month  | awk '{printf "%02d",$1-1}'`
fi

runid_out=${runid}                 # runid of your run
date_out=${year_out}_m${month_out} # restart date of your run

# Run code checking and update logs
[ $production -eq 1 ] && flgs="" || flgs="-d"   # use 'development' mode if production is off
strict_check $flgs $runid save-restarts canesm.cfg save_restart_files_${runid}
[ $? -ne 0 ] && exit 1

DATAPATH_DB1=$DATAPATH_DB
# append optional local database from another run
if [ -n "$DATAPATH_DB_OPT" ] ; then
  DATAPATH_DB1="$DATAPATH_DB1:$DATAPATH_DB_OPT"
fi
# modify DATAPATH_DB to search for restart files in system-wide database on ppp
DATAPATH_DB1="$DATAPATH_DB1:$SITESTORE_ROOT/../ppp_data/database_dir/datapath_`echo $CMCFEDEST | cut -f2 -d-`.db"
echo $DATAPATH_DB1

# extract year from date_out
year_out=`echo $date_out | cut -f1 -d'_'`
month_out=`echo $date_out | cut -f2 -d'_' | cut -c2-3`
# initial year
if [ $month_out -eq 12 ] ; then
  iyear=`expr $year_out + 1`
else
  iyear=$year_out
fi
echo year_out=$year_out month_out=$month_out iyear=$iyear

# compare restart months
month_in_a=`echo $date_in_a | cut -f2 -d'_' | cut -c2-3`
month_in_c=`echo $date_in_c | cut -f2 -d'_' | cut -c2-3`
if [ $month_in_a -ne $month_out -o $month_in_a -ne $month_in_c ] ; then
  echo "month_in_a=$month_in_a month_in_c=$month_in_c month_out=$month_out"
  echo "ERROR in save_restart_files: Input and output restart months must be the same."
  exit 1
fi

# create a temp dir not to interfere with files in local directory
curdir=`pwd`
tmpdir=$RUNPATH/tmp.restart.$$
mkdir -p $tmpdir
cd $tmpdir

# set a trap to remove $tmpdir on exit
trap "cleanup" 0 1 2 3 6 15
cleanup()
{
  exit_status=$?
  echo exit_status=$exit_status
  echo "Caught Signal ... cleaning up."
  rm -rf $tmpdir
  echo "Done cleanup ... quitting."
  if [ $exit_status -ne 0 ] ; then
    echo "*** ERROR in the save_restart_files script!!! ***"
    echo "Please verify input restart files are accessible:"
    echo "CanAM:  mc_${runid_in_a}_${date_in_a}"
    echo "CanCPL: mc_${runid_in_c}_${date_in_c}"
  fi
  exit $exit_status
}

# copy model job string into current directory
cp -p $curdir/$MODEL_JOB MODEL_JOB

# extract PARM/PARC from model job
xtrct_parmc MODEL_JOB

# extract value of delt
eval `grep delt parc_out`
delt=`echo $delt | tr -d ' '`
echo delt=$delt

echo runid_in_a=${runid_in_a} date_in_a=${date_in_a}
echo runid_in_c=${runid_in_c} date_in_c=${date_in_c}
echo runid_out=${runid_out} date_out=${date_out}

# # Access and save AN file
# env DATAPATH_DB=$DATAPATH_DB1 access x mc_${runid_in_a}_${date_in_a}_an
# save x mc_${runid_out}_${date_out}_an
# release x

# Save PARMC
cat PARM PARC > PARMC
save PARMC mc_${runid_out}_${date_out}_par
release PARMC

# Access and save AGCM restart
env DATAPATH_DB=$DATAPATH_DB1 access x mc_${runid_in_a}_${date_in_a}_rs_nmf
# Adjust time step
rstime_float1 x y restart_year=$year_out restart_month=$month_out iyear=$iyear delt=$delt
# Save RS file
save y mc_${runid_out}_${date_out}_rs_nmf
release x y

# Access and save CTEM restart
env DATAPATH_DB=$DATAPATH_DB1 access x mc_${runid_in_a}_${date_in_a}_ts_nmf
save x mc_${runid_out}_${date_out}_ts_nmf
release x

# Access and save Coupler restart
env DATAPATH_DB=$DATAPATH_DB1 access x mc_${runid_in_c}_${date_in_c}_cplrs nocp=off
save x mc_${runid_out}_${date_out}_cplrs
release x

# save environment and jobstring
env > MODEL_ENV
save  MODEL_ENV mc_${runid_out}_${date_out}_env
save  MODEL_JOB mc_${runid_out}_${date_out}_jobstring

# Access PHYS_PARM file
if [ $use_local_phys_parm -eq 0 ] ; then
  env DATAPATH_DB=$DATAPATH_DB1 access mc_${runid_in_a}_${date_in_a}_phys_parm mc_${runid_in_a}_${date_in_a}_phys_parm na
fi
if [ -s mc_${runid_in_a}_${date_in_a}_phys_parm ] ; then
  echo "*** Use PHYS_PARM from the parent run! ***"
else
  echo "*** Use PHYS_PARM from the local run directory! ***"
  cp -f $curdir/PHYS_PARM_${runid_out} mc_${runid_in_a}_${date_in_a}_phys_parm
fi

# Compare PHYS_PARM parameters
diff -E -B $curdir/PHYS_PARM_${runid_out} mc_${runid_in_a}_${date_in_a}_phys_parm && status_phys_parm=$? || status_phys_parm=$?

# Save PHYS_PARM file
save mc_${runid_in_a}_${date_in_a}_phys_parm mc_${runid_out}_${date_out}_phys_parm

# Access INLINE_DIAG_NL file
if [ $use_local_inline_diag_nl -eq 0 ] ; then
  env DATAPATH_DB=$DATAPATH_DB1 access mc_${runid_in_a}_${date_in_a}_inline_diag_nl mc_${runid_in_a}_${date_in_a}_inline_diag_nl na
fi
if [ -s mc_${runid_in_a}_${date_in_a}_inline_diag_nl ] ; then
  echo "*** Use INLINE_DIAG_NL from the parent run! ***"
else
  echo "*** Use INLINE_DIAG_NL from the local run directory! ***"
  cp -f $curdir/INLINE_DIAG_NL_${runid_out} mc_${runid_in_a}_${date_in_a}_inline_diag_nl
fi

# Compare INLINE_DIAG_NL parameters
diff -E -B $curdir/INLINE_DIAG_NL_${runid_out} mc_${runid_in_a}_${date_in_a}_inline_diag_nl && status_inline_diag_nl=$? || status_inline_diag_nl=$?

# Save INLINE_DIAG_NL file
save mc_${runid_in_a}_${date_in_a}_inline_diag_nl mc_${runid_out}_${date_out}_inline_diag_nl

# print a warning if parameter files differ
if [ $status_phys_parm -ne 0 -o $status_inline_diag_nl -ne 0 ] ; then
  if [ $status_phys_parm -ne 0 ] ; then
    echo "*** WARNING: local PHYS_PARM_${runid_out} differs from the PHYS_PARM file in \$RUNPATH ! ***"
    echo "*** Please review and edit PHYS_PARM file in \$RUNPATH, if needed. ***"
    echo "*** Use -p option to use PHYS_PARM_${runid_out} in the local run directory. ***"
  fi
  if [ $status_inline_diag_nl -ne 0 ] ; then
    echo "*** WARNING: local INLINE_DIAG_NL_${runid_out} differs from the INLINE_DIAG_NL file in \$RUNPATH ! ***"
    echo "*** Please review and edit INLINE_DIAG_NL file in \$RUNPATH, if needed. ***"
    echo "*** Use -d option to use INLINE_DIAG_NL_${runid_out} in the local run directory. ***"
  fi
  read -p "Press Enter to continue? " -n 1 -r
  echo
fi

cd $curdir
