#!/bin/bash
#############################################################################
##
## INITIAL DEVELOPMENT: Madlen Kimmritz, Sep 2019
##
## PURPOSE: 
## a) copy script on monthly feature detection from template to each case + member
##         and adapt
## b) prepare st_archive.sh and Tools-folders to determine features 
##
## INPUT
## (1) name of NorESM/NorCPM-submit setting file
## (2) name of MTK setting file
##
## REQUIREMENTS
## (1) dynlib available and required modules loaded
## (2) for prediction case (as st_archive.sh for prediction): call from run folder
##
#############################################################################

echo
echo " SCRIPT modify_submit_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
if [ $WF_IS_PREDICTION == 1 ]; then
  . $1
else
 source $1
fi

SCRIPTPATH=`readlink -f $0`
SCRIPTDIR=`dirname $SCRIPTPATH`
#############################################################################
#  check availability of DYNLIB and NORESM_AUTODETECT code and set links
#  same as in modify_setting_wefeat.sh in case calling that routine is swapped
if [ ! -d ${DL_ROOT} ] ; then
  echo "========================================================================= "
  echo "=      DYNLIB is not accessible via " ${DL_ROOT}
  echo "=      Please ensure that DYNLIB is installed,                          ="
  echo "=       required modules are loaded (see README_MTK.txt), and           ="
  echo "=       that the correct path DL_ROOT is provided in setting_MTK.sh     ="
  echo "=      We quit.                                                         ="
  echo "========================================================================= "
  exit 1
fi
if [ ! -d ${SCRIPTDIR}/../MTK/noresm_autodetect ] ; then
  echo "========================================================================= "
  echo "=      Package AUTODETECT not found. Please ensure that the script      ="
  echo "=      modify_setting_wefeat.sh has been executed correctly.            ="
  echo "=      We quit.                                                         ="
  echo "========================================================================= "
  exit 1
fi
#############################################################################
#

if [ $WF_IS_PREDICTION == 1 ]; then
  #case: PREDICTION
  #===========================================================================
  # (A) for all (new) cases and members: 
  #     (A1) copy noresm_autodetect function to the single cases/TOOLS folders
  #     (A2) adapt code, set names and member flags
  #
  #============================================================================
  #== TEMPLATE SETTING
  #NorCPM related
  ENS_PREFIX1=${PREFIX}_${START_YEAR1}${START_MONTH1}${START_DAY1}
  CASE1=${ENS_PREFIX1}_${MEMBERTAG}01
  if [ ! -e $CASESROOT/${ENS_PREFIX1}/$CASE1 ]
  then
    echo Template case $CASE1 does not exist. Please use create_template.sh to create.  
    echo  $CASESROOT/${ENS_PREFIX1}/$CASE1
    exit
  fi
  echo "#Dynlib related"
  CTAD1_PATH=${CASESROOT}/${ENS_PREFIX1}/${ENS_PREFIX1}_${MEMBERTAG}01/Tools/
  NAD_SCRIPT='cam_monthly_analyses.py'
  echo "Prepare cases for weather feature detection (modify_submit_MTK.sh)."
  echo "BEGIN LOOP OVER START DATES AND MEMBERS"
  for START_YEAR in $START_YEARS
  do
   for START_MONTH in $START_MONTHS
   do
     for START_DAY in $START_DAYS
     do  
       ENS_PREFIX=${PREFIX}_${START_YEAR}${START_MONTH}${START_DAY}
       for MEMBER in `seq -w 01 $MAX_MEMBERS`
       do
         CASE=${ENS_PREFIX}_${MEMBERTAG}${MEMBER} 
         CTADN_PATH=${CASESROOT}/${ENS_PREFIX}/${CASE}/Tools/ 
         if [ $CASE == $CASE1 ] 
         then 
           if grep -Fq "determine_MTK" ${CTADN_PATH}st_archive.sh
           then
             echo "=========================================================================================================="
             echo " ${CASE}/st_archive.sh already adapted for MTK application. No Change for this case and member."
             echo "=========================================================================================================="
             continue
           fi
            echo ++ PREPARE WEATHER FEATURE DECTECTION FOR CASE $CASE 
            #==== adapt local st_archive.sh (in beginning) of template =========================
            sed -n -i 'p;2a #== madlen.kimmritz@awi.de: Additional handling of weather feature detection.'  ${CTADN_PATH}st_archive.sh
            B1PATH=${1//\//\\/}  #replace every "/" by "\/"
            B2PATH=${2//\//\\/}  
            B3PATH=${CTADN_PATH//\//\\/}
            sed -n -i 'p;3a ACTUAL_PATH=`pwd`'  ${CTADN_PATH}st_archive.sh
            sed -n -i 'p;4a cd '${B3PATH}''  ${CTADN_PATH}st_archive.sh
            sed -n -i 'p;5a .\/determine_MTK.sh '${B1PATH}' '${B2PATH}''  ${CTADN_PATH}st_archive.sh
            sed -n -i 'p;6a cd ${ACTUAL_PATH}'  ${CTADN_PATH}st_archive.sh
            sed -n -i 'p;7a #== end: Additional handling of weather feature detection.'  ${CTADN_PATH}st_archive.sh
            sed -n -i 'p;8a #'  ${CTADN_PATH}st_archive.sh
            continue 
         fi   
         #================================= OTHER CASES THAN FIRST ==============
         echo ++ PREPARE WEATHER FEATURE DETECTION FOR CASE $CASE 
         #====  cam_monthly.py  =========================
         cp ${CTAD1_PATH}/${NAD_SCRIPT} ${CTADN_PATH}/.
         #== set paths and names
         CAM_RESN=$WORK"/archive/"$ENS_PREFIX"/"${CASE}"/wfe/"  #path to CAM output
         BPATH=${CAM_RESN//\//\\/}  #replace every "/" by "\/"
         sed -i s/"basepath =".*/"basepath = '"${BPATH}"'"/g ${CTADN_PATH}${NAD_SCRIPT} 
         sed -i s/"case =".*/"case = '"${ENS_PREFIX}"'"/g ${CTADN_PATH}${NAD_SCRIPT} 
         sed -i s/"member =".*/"member = '"${MEMBER}"'"/g ${CTADN_PATH}${NAD_SCRIPT} 
         #==== local st_archive.sh (beginning) =========================
         if grep -Fq "determine_MTK" ${CTADN_PATH}st_archive.sh
         then
            echo "=========================================================================================================="
            echo " ${CASE}/st_archive.sh already adapted for weather feature detection. No Change for this case and member."
            echo "=========================================================================================================="
            continue
         fi
         sed -n -i 'p;2a #== madlen.kimmritz@awi.de: Additional handling of weather feature detection.'  ${CTADN_PATH}st_archive.sh
         B1PATH=${1//\//\\/}  #replace every "/" by "\/"
         B2PATH=${2//\//\\/} 
         B3PATH=${CTADN_PATH//\//\\/}
         sed -n -i 'p;3a ACTUAL_PATH=`pwd`'  ${CTADN_PATH}st_archive.sh
         sed -n -i 'p;4a cd '${B3PATH}''  ${CTADN_PATH}st_archive.sh
         sed -n -i 'p;5a .\/determine_MTK.sh '${B1PATH}' '${B2PATH}''  ${CTADN_PATH}st_archive.sh
         sed -n -i 'p;6a cd ${ACTUAL_PATH}'  ${CTADN_PATH}st_archive.sh
         sed -n -i 'p;7a #== end: Additional handling of weather feature detection.'  ${CTADN_PATH}st_archive.sh
         sed -n -i 'p;8a #'  ${CTADN_PATH}st_archive.sh
       done #MEMBER
     done   #START_DAY
   done     #START_MONTH
  done      #START_YEAR
#
#
#############################################################################
# case: ANALYSIS
else
  #===========================================================================
  # (B) for all (new) cases and members: 
  #     (B1) copy noresm_autodetect function to the single cases/TOOLS folders
  #     (B2) adapt code, set names and member flags
  #     (B3) set the required links 
  #         (in contrast to prediction case, they are not copied from template)
  #============================================================================
  #== TEMPLATE SETTING
  #NorCPM related
  CASE1=${VERSION}01
  CASESROOT=`dirname $SCRIPTPATH`/../cases
  if [ ! -e $CASESROOT/${CASEDIR}/$CASE1 ]
  then
    echo Template case $CASE1 does not exist. Please use create_ensemble.sh to create  
    echo Template $CASESROOT/${CASEDIR}/$CASE1 "(member 01) and all other case members" 
    exit
  fi
  echo "#Dynlib related"
  CTAD1_PATH=${CASESROOT}/${CASEDIR}/${CASE1}/Tools/
  NAD_SCRIPT='cam_monthly_analyses.py'
  echo "Prepare cases for weather feature detection (modify_submit_MTK.sh)."
  echo "BEGIN LOOP OVER MEMBERS"
       for MEMBER in `seq -w 01 $ENSSIZE`
       do
         CASE=${VERSION}${MEMBER} 
         CTADN_PATH=${CASESROOT}/${CASEDIR}/${CASE}/Tools/ 
         if [ $CASE == $CASE1 ] 
         then 
           if grep -Fq "determine_MTK" ${CTADN_PATH}st_archive.sh
           then
             echo "=========================================================================================================="
             echo " ${CASE}/st_archive.sh already adapted for MTK application. No Change for this case and member."
             echo "=========================================================================================================="
             continue
           fi
            echo ++ PREPARE WEATHER FEATURE DECTECTION FOR CASE $CASE 
            #==== adapt local st_archive.sh (in beginning) of template =========================
            sed -n -i 'p;2a #== madlen.kimmritz@awi.de: Additional handling of weather feature detection.'  ${CTADN_PATH}st_archive.sh
            B1PATH=${1//\//\\/}  #replace every "/" by "\/"
            B2PATH=${2//\//\\/}  
            B3PATH=${CTADN_PATH//\//\\/}
            sed -n -i 'p;3a ACTUAL_PATH=`pwd`'  ${CTADN_PATH}st_archive.sh
            sed -n -i 'p;4a cd '${B3PATH}''  ${CTADN_PATH}st_archive.sh
            sed -n -i 'p;5a .\/determine_MTK.sh '${B1PATH}' '${B2PATH}''  ${CTADN_PATH}st_archive.sh
            sed -n -i 'p;6a cd ${ACTUAL_PATH}'  ${CTADN_PATH}st_archive.sh
            sed -n -i 'p;7a #== end: Additional handling of weather feature detection.'  ${CTADN_PATH}st_archive.sh
            sed -n -i 'p;8a #'  ${CTADN_PATH}st_archive.sh
            continue 
         fi   
         #================================= OTHER CASES THAN FIRST ==============
         echo ++ PREPARE WEATHER FEATURE DETECTION FOR CASE $CASE 
         #====  set required links and copy cam_monthly_analyses.py from template member 01 
         ln -sf ${CASESROOT}/../MTK/noresm_autodetect/cam_detection_functions.py ${CTADN_PATH}/cam_detection_functions.py
         ln -sf ${CASESROOT}/../MTK/noresm_autodetect/cam_determine_thresholds.py ${CTADN_PATH}/cam_determine_thresholds.py
         ln -sf ${CASESROOT}/../MTK/determine_MTK.sh ${CTADN_PATH}/.
         ln -sf ${DL_ROOT}/lib ${CTADN_PATH}/dynlib  
         #====  cam_monthly.py  =========================
         cp ${CTAD1_PATH}/${NAD_SCRIPT} ${CTADN_PATH}/.
         #== set paths and names
         CAM_RESN=$WORK"/archive/"$CASEDIR"/"${CASE}"/wfe/"  #path to CAM output
         BPATH=${CAM_RESN//\//\\/}  #replace every "/" by "\/"
         sed -i s/"basepath =".*/"basepath = '"${BPATH}"'"/g ${CTADN_PATH}${NAD_SCRIPT} 
         sed -i s/"case =".*/"case = '"${CASEDIR}"'"/g ${CTADN_PATH}${NAD_SCRIPT} 
         sed -i s/"member =".*/"member = '"${MEMBER}"'"/g ${CTADN_PATH}${NAD_SCRIPT} 
         #==== local st_archive.sh (beginning) =========================
         if grep -Fq "determine_MTK" ${CTADN_PATH}st_archive.sh
         then
            echo "=========================================================================================================="
            echo " ${CASE}/st_archive.sh already adapted for weather feature detection. No Change for this case and member."
            echo "=========================================================================================================="
            continue
         fi
         sed -n -i 'p;2a #== madlen.kimmritz@awi.de: Additional handling of weather feature detection.'  ${CTADN_PATH}st_archive.sh
         B1PATH=${1//\//\\/}  #replace every "/" by "\/"
         B2PATH=${2//\//\\/} 
         B3PATH=${CTADN_PATH//\//\\/}
         sed -n -i 'p;3a ACTUAL_PATH=`pwd`'  ${CTADN_PATH}st_archive.sh
         sed -n -i 'p;4a cd '${B3PATH}''  ${CTADN_PATH}st_archive.sh
         sed -n -i 'p;5a .\/determine_MTK.sh '${B1PATH}' '${B2PATH}''  ${CTADN_PATH}st_archive.sh
         sed -n -i 'p;6a cd ${ACTUAL_PATH}'  ${CTADN_PATH}st_archive.sh
         sed -n -i 'p;7a #== end: Additional handling of weather feature detection.'  ${CTADN_PATH}st_archive.sh
         sed -n -i 'p;8a #'  ${CTADN_PATH}st_archive.sh
       done #MEMBER
  #==================================================================
fi
echo "modify_submit_MTK.sh: done"

 
