#!/bin/bash
#############################################################################
##
## INITIAL DEVELOPMENT: Madlen Kimmritz, Sep 2019
##
## PURPOSE: 
## (0) check availability of code 
##     (if not available, sets noresm_autodetect into place and links dynlib)
## (1) adapt local template version of cam_monthly_analyses.py to derive the 
##           required feature diagnostics
## (2) adapt cam.bldnmlst of template case to enable 6-hrly output 
##           needed for DYNLIB and for user (=DYN_ADD_OUT)
##
## INPUT
## (1) name of NorESM/NorCPM-submit setting file
## (2) name of MTK setting file 
#############################################################################

echo
echo " SCRIPT modify_setting_MTK.sh "
echo "       USAGE: ./`basename $0` <path to settings file> <path to we_feat settings file>" 
echo "       EXAMPLE: ./`basename $0` use_cases/prediction_test.in use_cases/setting_MTK.sh" 
echo
source $2
. $1

#============================================================================
if [ $WF_IS_PREDICTION == 1 ] && [ "${STOP_OPTION}" != "nmonths" ] && [ "${STOP_OPTION}" != 'nyears' ]; then 
  echo "STOP_OPTION=" ${STOP_OPTION}
  echo "Invalid choice of STOP_OPTION (see "${1}"). Required: STOP_OPTION = nmonths or STOP_OPTION = nyears."
  echo "We quit."
  exit 1
fi

#============================================================================
# set variables and paths
SCRIPTPATH=`readlink -f $0`
SCRIPTDIR=`dirname $SCRIPTPATH`
NAD_SCRIPT='cam_monthly_analyses.py'
if [ $WF_IS_PREDICTION == 1 ]; then
  DYN_CASENAME=${PREFIX}_${START_YEAR1}${START_MONTH1}${START_DAY1} 
  CTAD_PATH=${CASESROOT}/${DYN_CASENAME}/${DYN_CASENAME}_${MEMBERTAG}01/Tools/    #path to local script of detection function
  CAM_BLDNML=${CASESROOT}/${DYN_CASENAME}/${DYN_CASENAME}_${MEMBERTAG}01/Buildconf/cam.buildnml.csh
  CAM_RES1=$WORK"/archive/"$DYN_CASENAME"/"${DYN_CASENAME}_${MEMBERTAG}"01/wfe/"  #path of CAM out (of template) for dynlib (in archive due to st_archive)
else
  DYN_CASENAME=${CASEDIR}
  CASESROOT=${SCRIPTDIR}/../cases 
  CTAD_PATH=${CASESROOT}/${DYN_CASENAME}/${VERSION}01/Tools/    #path to local script of detection function
  CAM_BLDNML=${CASESROOT}/${DYN_CASENAME}/${VERSION}01/Buildconf/cam.buildnml.csh
  CAM_RES1=$WORK"/archive/"$DYN_CASENAME"/"${VERSION}"01/wfe/"  #path of CAM out (of template) for dynlib (in archive due to st_archive)
fi

AD_PATH=${SCRIPTDIR}/../MTK/noresm_autodetect/
NEW_WF_ANALYSIS=${CTAD_PATH}/${NAD_SCRIPT}

#============================================================================
#  check availability of DYNLIB and NORESM_AUTODETECT code and set links
echo "  (-1) check availability of code related to DYNLIB"
if [ ! -d ${DL_ROOT} ] ; then
  echo "========================================================================= "
  echo "=      DYNLIB is not accessible via " ${DL_ROOT}.
  echo "=      We quit.                                                         ="
  echo "========================================================================= "
  exit 1
fi

if [ ! -d ${SCRIPTDIR}/../MTK/noresm_autodetect ] ; then
  cd ${SCRIPTDIR}/../MTK/
  git clone https://git.app.uib.no/Clemens.Spensberger/noresm_autodetect.git
  ln -sf ${DL_ROOT}/lib noresm_autodetect/dynlib
  chmod -R 755 noresm_autodetect
  cd -
fi

#============================================================================
#(0) identify needed additional 6-hourly output
echo "  (0) provided DYNLIB diagostics and 6-hourly CAM output will be: "
#== CAM output flags
U_OUT=0; V_OUT=0; Z_OUT=0; T_OUT=0; Q_OUT=0; PSL_OUT=0; PHIS_OUT=0; PS_OUT=1; #PS needed for interpolation (i.e. for all)
#== DYN output flags
FJETS='False'; FRWB='False'; FFRONTLIN='False'; FFRONTVOL='False'; FEDDY='False'; FCYCL='False'; FBLOCK='False';

for item in ${DYN_OUT[@]}
do
  if [ 'JETS' == "$item" ]; then
    U_OUT=1; V_OUT=1; FJETS='True';
  elif [ 'RWB' == "$item" ]; then
    Z_OUT=1; FRWB='True';
  elif [ 'FRONTLINES' == "$item" ]; then
    U_OUT=1; V_OUT=1; T_OUT=1; Q_OUT=1; FFRONTLIN='True';
  elif [ 'FRONTVOLUMES' == "$item" ]; then
    T_OUT=1; Q_OUT=1; FFRONTVOL='True';
  elif [ 'EDDYVAR' == "$item" ]; then
    U_OUT=1; V_OUT=1; Z_OUT=1; T_OUT=1; Q_OUT=1; FEDDY='True'; 
  elif [ 'CYCLTRACK' == "$item" ]; then
    PSL_OUT=1; PHIS_OUT=1; FCYCL='True';
  elif [ 'BLOCK' == "$item" ]; then
    Z_OUT=1; FBLOCK='True';
  fi
done

#==== create list of CAM variables for DYNLIB
CAM_OUT=()
if [ $U_OUT == 1 ]; then
   CAM_OUT+=('U:I');
fi 
if [ $V_OUT == 1 ]; then
   CAM_OUT+=('V:I');
fi 
if [ $Z_OUT == 1 ]; then
   CAM_OUT+=('Z3:I');
fi 
if [ $T_OUT == 1 ]; then
   CAM_OUT+=('T:I');
fi 
if [ $Q_OUT == 1 ]; then
   CAM_OUT+=('Q:I');
fi 
if [ $PS_OUT == 1 ]; then
  CAM_OUT+=('PS:I');
fi 
if [ $PSL_OUT == 1 ]; then
   CAM_OUT+=('PSL:I');
fi 
if [ $PHIS_OUT == 1 ]; then
   CAM_OUT+=('PHIS:I');
fi 

echo "       Monthly DYNLIB output: " ${DYN_OUT[@]}
#echo "       6-hourly output for DYNLIB (dumped): " ${CAM_OUT[@]}
echo "       6-hourly output (retained): " ${DYN_ADD_OUT[@]}
echo

#==========================================================================
# (0) check whether DYN_H1 and DYN_H2 have the correct value and correct
if [ ! -f ${CAM_BLDNML} ] ; then
  echo "File " ${CAM_BLDNML} " does not exist; we quit."
  exit 1
fi

ccount="`grep -c "fincl" ${CAM_BLDNML}`"
if (( ${DYN_H1} != ${ccount} )); then
  echo "DYN_H1 will be set to ${ccount} and DYN_H2 to $((ccount +1)) in $2"
  sed -i s/"DYN_H1=".*/"DYN_H1="${ccount}/g ${2}
  sed -i s/"DYN_H2=".*/"DYN_H2="$((ccount +1))/g ${2}
  let "DYN_H1=ccount"
  let "DYN_H2=ccount+1"
fi 
if (( ${DYN_H2} != $((DYN_H1 +1)) )); then
  echo "DYN_H1+1 = DYN_H2 required. This has been corrected in $2"
  let "DYN_H2=DYN_H1+1"
  sed -i s/"DYN_H2=".*/"DYN_H2="${DYN_H2}/g ${2}
fi 

#==========================================================================
# (1a) adapt cam_monthly_analyses.py 
echo "  (1a) copy ${NAD_SCRIPT} to ${NEW_WF_ANALYSIS}"
echo "  (1b) adapt ${NAD_SCRIPT} "
#==
if [ ! -f ${NEW_WF_ANALYSIS} ] ; then
  cp ${AD_PATH}/${NAD_SCRIPT} ${NEW_WF_ANALYSIS} 
fi
#== set diagnostics
sed -i s/"CALC_JETS =".*/"CALC_JETS = "${FJETS}/g ${NEW_WF_ANALYSIS}
sed -i s/"CALC_RWB =".*/"CALC_RWB = "${FRWB}/g ${NEW_WF_ANALYSIS}
sed -i s/"CALC_FRONTLINES =".*/"CALC_FRONTLINES = "${FFRONTLIN}/g ${NEW_WF_ANALYSIS}
sed -i s/"CALC_FRONTVOLUMES =".*/"CALC_FRONTVOLUMES = "${FFRONTVOL}/g ${NEW_WF_ANALYSIS}
sed -i s/"CALC_EDDYVAR =".*/"CALC_EDDYVAR = "${FEDDY}/g ${NEW_WF_ANALYSIS}
sed -i s/"CALC_CYC =".*/"CALC_CYC = "${FCYCL}/g ${NEW_WF_ANALYSIS}
sed -i s/"CALC_BLOCK =".*/"CALC_BLOCK = "${FBLOCK}/g ${NEW_WF_ANALYSIS}
#== set paths and names
#=== high frequ output will be stored/linked in STA/wfe/ without any atm/hist/ structure.
sed -i s/"conf.file_std = ".*/"conf.file_std = '{case}_mem{member}.cam2.{output}.{yr:04d}-{month:02d}-{day:02d}-21600'"/g ${NEW_WF_ANALYSIS}
#==archive folder 
BPATH=${CAM_RES1//\//\\/}  #replace every "/" by "\/"
sed -i s/"basepath =".*/"basepath = '"${BPATH}"'"/g ${NEW_WF_ANALYSIS} 
sed -i s/"case =".*/"case = '"${DYN_CASENAME}"'"/g ${NEW_WF_ANALYSIS} 
#sed -i s/"output =".*/"output = 'h1'"/g ${NEW_WF_ANALYSIS}
let ACT_N1="DYN_H1"
sed -i s/"output =".*/"output = 'h"${ACT_N1}"'"/g ${NEW_WF_ANALYSIS}
#===========================
chmod 755 ${NEW_WF_ANALYSIS}
echo 
#==========================================================================
# (1b) link required scripts 
  chmod 755 ${AD_PATH}/cam_detection_functions.py
  chmod 755 ${AD_PATH}/cam_determine_thresholds.py
  ln -sf ${AD_PATH}/cam_detection_functions.py ${CTAD_PATH}/cam_detection_functions.py
  ln -sf ${AD_PATH}/cam_determine_thresholds.py ${CTAD_PATH}/cam_determine_thresholds.py
  ln -sf ${AD_PATH}/../determine_MTK.sh ${CTAD_PATH}/. 
  ln -sf ${DL_ROOT}/lib ${CTAD_PATH}/dynlib  
#================================================================
# (2) adapt cam.bldnmlst of template for
#      - 6-hrly output for DYNLIB (dumped afterwards)
#           -- 4 record/file daily               (h1)
#      - requested 6-hrly output (optional, retained)
#           -- 4 records/file daily              (h2)
#
#          info on bldnml variables: 
#          mfilt= #records/file, nhtfrq = time interval

echo "  (2) adapt CAM build-namelist"
#=======================
linem="`grep "mfilt" ${CAM_BLDNML}`"
linen="`grep "nhtfrq" ${CAM_BLDNML}`"
#=======================
let ACT_N1="DYN_H1+1"
let ACT_N2="DYN_H2+1"
if (( ${#DYN_ADD_OUT[@]} )); then
  # dynlib related output (dumped after usage) and additional 6hourly output (retained)
  linemm=${linem}",4,4"
  linenn=${linen}",-6,-6"
  sed -i "s/${linem}/${linemm}/" ${CAM_BLDNML}
  sed -i "s/${linen}/${linenn}/" ${CAM_BLDNML}

  hifr="${CAM_OUT[@]}";  hifr=`echo ${hifr// /"', '"}`; 
  hifr=" fincl"${ACT_N1}" = '"${hifr}"'";                 # list of output vars for h1
  sed -i "s/${linemm}/${hifr}\n${linemm}/" ${CAM_BLDNML}  # insert list into bldnml

  hifr="${DYN_ADD_OUT[@]}";  hifr=`echo ${hifr// /"', '"}`; 
  hifr=" fincl"${ACT_N2}" = '"${hifr}"'";                 # list of output vars for h2
  sed -i "s/${linemm}/${hifr}\n${linemm}/" ${CAM_BLDNML}  # insert list into bldnml
else
  # only dynlib related output (dumped after usage)
  linemm=${linem}",4"
  linenn=${linen}",-6"
  sed -i "s/${linem}/${linemm}/" ${CAM_BLDNML}
  sed -i "s/${linen}/${linenn}/" ${CAM_BLDNML}

  hifr="${CAM_OUT[@]}";  hifr=`echo ${hifr// /"', '"}`; 
  hifr=" fincl"${ACT_N1}" = '"${hifr}"'";                 # list of output vars for h1
  sed -i "s/${linemm}/${hifr}\n${linemm}/" ${CAM_BLDNML}  # insert list into bldnml
fi

echo "modify_setting_MTK.sh: done"

 
