#!/bin/bash
set -e
#
# load files from tape and save them for a new runid / year
#
#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
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=${parent_runid}        # Parent runid to be used as restart
date_in=${parent_branch_time}   # Restart date in the parent run as YYYY_m12

# use parent arhive settings from canesm.cfg but can be overwritten below
archive_user=${parent_archive_user}     # username of the RS archive, if you know (e.g cpd103)
archive_class=${parent_archive_class}   # long or short term class

# overwrite archive settings, if needed
#archive_user=unknown           # insert username of the RS archive, if you know (e.g cpd103)
#archive_class=crd_cccma        # long term
#archive_class=crd_short_term   # short term

Usage='Usage:

  tapeload_rs [-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

# output runid and date (you can overwrite it here if needed)
runid_out=${runid}                 # runid of your run
date_out=${year_out}_m${month_out} # restart date of your run YYYY_m12

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

# 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=`echo $date_in | cut -f2 -d_ | cut -c2-3`
if [ $month_in -ne $month_out ] ; then
  echo "month_in=$month_in month_out=$month_out"
  echo "ERROR in tapeload_rs: 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 tapeload_rs script!!! ***"
    echo "Please verify input restart files are archived:"
    echo "mc_${runid_in}_${date_in}"
  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=${runid_in} date_in=${date_in}
echo runid_out=${runid_out} date_out=${date_out}

# find the latest "rs" archive
if [ "$archive_user" = "unknown" -o "$archive_user" = "" ] ; then
  archive_user_arg="-U"
else
  archive_user_arg="-u $archive_user"
fi
hpcarchive_pfx="rs_${runid_in}_${date_in}_"
hpcarchive=`hpcarchive -p $archive_class $archive_user_arg -L -x -s -c "^$hpcarchive_pfx" | grep $hpcarchive_pfx | head -1`
if [ "$hpcarchive" = "" ] ; then
  echo "WARNING: no HPC archive is found with prefix: $hpcarchive_pfx!"
  # if not found, try "mc" archive
  hpcarchive_pfx="mc_${runid_in}_${date_in}_"
  echo "Try another prefix: $hpcarchive_pfx"
  hpcarchive=`hpcarchive -p $archive_class $archive_user_arg -L -x -s -c "^$hpcarchive_pfx" | grep $hpcarchive_pfx | head -1`
  if [ "$hpcarchive" = "" ] ; then
    echo "ERROR: no HPC archive is found with this prefix: $hpcarchive_pfx!"
    exit 1
  fi
fi
hpcarcuser=`echo $hpcarchive | cut -f1 -d' ' | cut -c2-`
hpcarcname=${hpcarchive##* }

# Retrive full tape archive
echo hpcarchive -p $archive_class -u ${hpcarcuser} -b -r -c ${hpcarcname}
     hpcarchive -p $archive_class -u ${hpcarcuser} -b -r -c ${hpcarcname}

# # Save AN file
# save mc_${runid_in}_${date_in}_an mc_${runid_out}_${date_out}_an

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

# Adjust time step
rstime_float1 mc_${runid_in}_${date_in}_rs_nmf 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 y

# Save CTEM restart
save mc_${runid_in}_${date_in}_ts_nmf mc_${runid_out}_${date_out}_ts_nmf

# Untar the ocean restart and save
if [ "$config" != "AMIP" ] ; then
  if [ -s mc_${runid_in}_${date_in}_nemors.tar ] ; then
    mkdir mc_${runid_out}_${date_out}_nemors
    cd mc_${runid_out}_${date_out}_nemors
    mv ../mc_${runid_in}_${date_in}_nemors.tar .
    tar -xvf mc_${runid_in}_${date_in}_nemors.tar
    release mc_${runid_in}_${date_in}_nemors.tar
    cd ../
    save mc_${runid_out}_${date_out}_nemors mc_${runid_out}_${date_out}_nemors
  fi
fi

# Deal with the coupler restart
mkdir mc_${runid_out}_${date_out}_cplrs
mv cplrs* mc_${runid_out}_${date_out}_cplrs/
#mv *_cpl.exe mc_${runid_out}_${date_out}_cplrs/ # SK: do we need to move this file?
save mc_${runid_out}_${date_out}_cplrs mc_${runid_out}_${date_out}_cplrs

# 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
  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}_${date_in}_phys_parm
fi

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

# Save PHYS_PARM file
save mc_${runid_in}_${date_in}_phys_parm mc_${runid_out}_${date_out}_phys_parm

# Access INLINE_DIAG_NL file
if [ $use_local_inline_diag_nl -eq 0 -a -s mc_${runid_in}_${date_in}_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}_${date_in}_inline_diag_nl
fi

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

# Save INLINE_DIAG_NL file
save mc_${runid_in}_${date_in}_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
