#-Q- curie ######################
#-Q- curie ## CURIE   TGCC/CEA ##
#-Q- curie ######################
#-Q- curie #MSUB -r MONITORING     # Nom du job
#-Q- curie #MSUB -o MONITORING.out_%I
#-Q- curie #MSUB -e MONITORING.out_%I
#-Q- curie #MSUB -n 1              # Reservation du processus
#-Q- curie #MSUB -T 80000          # Limite de temps elapsed du job
#-Q- curie #MSUB -q ::default_node::
#-Q- curie #MSUB -c ::default_core::
#-Q- curie #MSUB -Q normal
#-Q- curie #MSUB -A ::default_project::
#-Q- curie set +x
#-Q- irene ######################
#-Q- irene ## IRENE   TGCC/CEA ##
#-Q- irene ######################
#-Q- irene #MSUB -r MONITORING    # Job name
#-Q- irene #MSUB -o MONITORING.out_%I
#-Q- irene #MSUB -e MONITORING.out_%I
#-Q- irene #MSUB -n 1             # Number of cores
#-Q- irene #MSUB -T 80000         # Maximum elapsed time
#-Q- irene #MSUB -q ::default_node:: 
#-Q- irene #MSUB -c ::default_core::
#-Q- irene #MSUB -Q normal
#-Q- irene #MSUB -A ::default_post_project::
#-Q- irene #MSUB -m store,work,scratch
#-Q- irene set +x
#-Q- irene-amd ######################
#-Q- irene-amd ## IRENE   TGCC/CEA ##
#-Q- irene-amd ######################
#-Q- irene-amd #MSUB -r MONITORING     # Job name
#-Q- irene-amd #MSUB -o MONITORING.out_%I
#-Q- irene-amd #MSUB -e MONITORING.out_%I
#-Q- irene-amd #MSUB -n 1              # Number of cores
#-Q- irene-amd #MSUB -T 80000          # Maximum elapsed time
#-Q- irene-amd #MSUB -q ::default_node::
#-Q- irene-amd #MSUB -c ::default_core::
#-Q- irene-amd #MSUB -Q normal
#-Q- irene-amd #MSUB -A ::default_post_project::
#-Q- irene-amd #MSUB -m store,work,scratch
#-Q- irene-amd set +x
#-Q- jeanzay #!/bin/ksh 
#-Q- jeanzay ######################
#-Q- jeanzay ## JEANZAY    IDRIS ##
#-Q- jeanzay ######################
#-Q- jeanzay #SBATCH --job-name=MONITORING         # Job Name
#-Q- jeanzay #SBATCH --output=MONITORING.out_%J    # standard output
#-Q- jeanzay #SBATCH --error=MONITORING.out_%J     # error output
#-Q- jeanzay #SBATCH --ntasks=1                    # Number of core
#-Q- jeanzay #SBATCH --hint=nomultithread          # 1 processus MPI par coeur physique (pas d'hyperthreading)
#-Q- jeanzay #SBATCH --time=10:00:00               # Wall clock limit (seconds)
#-Q- jeanzay #SBATCH --account ::default_project::@cpu
#-Q- jeanzay #SBATCH --partition=prepost
#-Q- jeanzay set +x
#-Q- ada #!/bin/ksh
#-Q- ada #######################
#-Q- ada ## ADA         IDRIS ##
#-Q- ada #######################
#-Q- ada # @ job_type = mpich
#-Q- ada # @ requirements = (Feature == "prepost")
#-Q- ada # Temps Elapsed max. d'une requete hh:mm:ss
#-Q- ada # @ wall_clock_limit = 4:00:00
#-Q- ada # Memory required for ferret (_SEP _MAR variables)
#-Q- ada # @ as_limit = 30Gb
#-Q- ada # Nom du travail LoadLeveler
#-Q- ada # @ job_name   = MONITORING
#-Q- ada # Fichier de sortie standard du travail
#-Q- ada # @ output     = $(job_name).$(jobid)
#-Q- ada # Fichier de sortie d'erreur du travail
#-Q- ada # @ error      =  $(job_name).$(jobid)
#-Q- ada # pour recevoir un mail en cas de depassement du temps Elapsed (ou autre pb.)
#-Q- ada # @ notification = error
#-Q- ada # @ environment  = $DEBUG_debug ; $BigBrother ; $postProcessingStopLevel ; $POST_DIR ; $Script_Post_Output ; $SUBMIT_DIR ; $libIGCM ; $StandAlone ; $RESOL_ATM ; $RESOL_OCE ; $RESOL_ICE ; $RESOL_MBG ; $RESOL_SRF ; wall_clock_limit=$(wall_clock_limit)
#-Q- ada # @ queue
#-Q- lxiv8 ######################
#-Q- lxiv8 ## OBELIX      LSCE ##
#-Q- lxiv8 ######################
#-Q- lxiv8 #PBS -N MONITORING
#-Q- lxiv8 #PBS -m a
#-Q- lxiv8 #PBS -j oe
#-Q- lxiv8 #PBS -q medium
#-Q- lxiv8 #PBS -o MONITORING.$$
#-Q- lxiv8 #PBS -S /bin/ksh
#-Q- ifort_CICLAD ######################
#-Q- ifort_CICLAD ##   CICLAD    IPSL ##
#-Q- ifort_CICLAD ######################
#-Q- ifort_CICLAD #PBS -N MONITORING
#-Q- ifort_CICLAD #PBS -m a
#-Q- ifort_CICLAD #PBS -j oe
#-Q- ifort_CICLAD #PBS -q std
#-Q- ifort_CICLAD #PBS -S /bin/ksh
#-Q- default #!/bin/ksh
#-Q- default ##################
#-Q- default ## DEFAULT HOST ##
#-Q- default ##################

#**************************************************************
# Author: Sebastien Denvil
# Contact: Sebastien.Denvil__at__ipsl.jussieu.fr
# $Revision:: 1525                                     $ Revision of last commit
# $Author:: cetlod                                     $ Author of last commit
# $Date:: 2020-04-27 10:39:22 +0200 (Mon, 27 Apr 2020) $ Date of last commit
# IPSL (2006)
#  This software is governed by the CeCILL licence see libIGCM/libIGCM_CeCILL.LIC
#
#**************************************************************

#set -eu
#set -vx

date

#-Q- ada export OMP_NUM_THREADS=1

#D- Task type DO NOT CHANGE (computing, post-processing or checking)
TaskType=post-processing

########################################################################

#D- Flag to determine if this job in a standalone mode
#D- Default : value from AA_job if any
StandAlone=${StandAlone:=true}

#D- Path to libIGCM
#D- Default : value from AA_job if any
# WARNING For StandAlone use : To run this script on some machine (ada and cesium)
# WARNING you must check MirrorlibIGCM variable in sys library.
# WARNING If this variable is true, you must use libIGCM_POST path instead
# WARNING of your running libIGCM directory.
libIGCM=${libIGCM:=::modipsl::/libIGCM}

#D- Increased verbosity (1, 2, 3)
#D- Default : value from AA_job if any
Verbosity=${Verbosity:=3}

#D- Low level debug : to bypass lib test checks and stack construction
#D- Default : value from AA_job if any
DEBUG_debug=${DEBUG_debug:=false}

#D- TEMPORARY Flag to determine atmospheric resolution
#D- Default : value from atmospheric driver if any
RESOL_ATM=${RESOL_ATM:=ALL}

#D- Flag to determine surface resolution
#D- Default : value from surface driver if any
RESOL_SRF=${RESOL_SRF:=ALL}

#D- Flag to determine surface resolution
#D- Default : value from surface driver if any
RESOL_SBG=${RESOL_SBG:=ALL}

#D- TEMPORARY Flag to determine ocean resolution
#D- Default : value from ocean driver if any
RESOL_OCE=${RESOL_OCE:=ORCA2}

#D- TEMPORARY Flag to determine ice resolution
#D- Default : value from ice driver if any
RESOL_ICE=${RESOL_OCE:=ORCA2}

#D- TEMPORARY Flag to determine marine biogeochemistry resolution
#D- Default : value from ice driver if any
RESOL_MBG=${RESOL_OCE:=ORCA2}

######################################################################

. ${libIGCM}/libIGCM_debug/libIGCM_debug.ksh
. ${libIGCM}/libIGCM_card/libIGCM_card.ksh
. ${libIGCM}/libIGCM_date/libIGCM_date.ksh
#-------
. ${libIGCM}/libIGCM_sys/libIGCM_sys.ksh
. ${libIGCM}/libIGCM_config/libIGCM_config.ksh
#-------
RUN_DIR=${RUN_DIR_PATH}
IGCM_sys_MkdirWork ${RUN_DIR}
IGCM_sys_Cd ${RUN_DIR}
#-------
( ${DEBUG_debug} ) && IGCM_debug_Check
( ${DEBUG_debug} ) && IGCM_card_Check
( ${DEBUG_debug} ) && IGCM_date_Check

######################################################################

#set -vx

# ------------------------------------------------------------------
# Test if all was right before proceeding further
# ------------------------------------------------------------------
IGCM_debug_Verif_Exit

if [ ${StandAlone} = true ] ; then
  CARD_DIR=${SUBMIT_DIR}
else
  CARD_DIR=${RUN_DIR}
  IGCM_sys_Get_Master ${SUBMIT_DIR}/config.card ${RUN_DIR_PATH}
  IGCM_sys_Get_Master ${SUBMIT_DIR}/run.card    ${RUN_DIR_PATH}
  IGCM_sys_Get_Master ${SUBMIT_DIR}/COMP        ${RUN_DIR_PATH}
  IGCM_sys_Get_Master ${SUBMIT_DIR}/POST        ${RUN_DIR_PATH}
fi

#==================================
# First of all
#
# Read libIGCM compatibility version in config.card
# Read UserChoices section
# Read Ensemble section
# Read Post section
# Define all netcdf output directories
#==================================
IGCM_config_CommonConfiguration ${CARD_DIR}/config.card

# ------------------------------------------------------------------
# Activate BigBrother so as to supervise this job
# ------------------------------------------------------------------
IGCM_debug_BigBro_Initialize

#==================================
# Read ListOfComponents section:
IGCM_card_DefineArrayFromSection ${CARD_DIR}/config.card ListOfComponents

# Create R_FIGR that has been defined by IGCM_config_CommonConfiguration
IGCM_sys_MkdirArchive ${R_FIGR}
#
IGCM_sys_TestDirArchive ${R_FIGR}/MONITORING
if [ $? = 0 ] ; then
  IGCM_debug_Print 1 "Get MONITORING directory from archive"
  IGCM_sys_Get_Dir ${R_FIGR}/MONITORING ${RUN_DIR}
else
  IGCM_debug_Print 1 "MONITORING first pass. Nothing has been done before"
fi
# --------------------------------------------
# Insert your commands between III...III lines
# and precise produced directories to save
# IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII

for comp in ${config_ListOfComponents[*]} ; do
  IGCM_debug_Print 1 "################## Component: ${comp} ######################"
  liste_file_monitoring=""
  IGCM_card_DefineArrayFromOption ${CARD_DIR}/config.card ListOfComponents ${comp}
  eval compname=\${config_ListOfComponents_${comp}[0]}                > /dev/null 2>&1

  PATH_monitoring_file=""
  eval monitoring_file=monitoring01_${compname}_\${RESOL_${comp}}.cfg > /dev/null 2>&1
  if [[ -d ${CARD_DIR}/POST && -f ${CARD_DIR}/POST/${monitoring_file} ]] ; then
    PATH_monitoring_file=${CARD_DIR}/POST/${monitoring_file}
  elif [[ -d ${CARD_DIR}/POST && -f ${CARD_DIR}/POST/monitoring01_${compname}.cfg ]] ; then
    PATH_monitoring_file=${CARD_DIR}/POST/monitoring01_${compname}.cfg
  elif [ -f ${FER_ATLAS}/${monitoring_file} ] ; then
    PATH_monitoring_file=${FER_ATLAS}/${monitoring_file}
  else
    IGCM_debug_Print 1 "No monitoring file found for this component. Was expecting ${monitoring_file}"
    IGCM_debug_Print 1 "Step to next component"
    continue
  fi
  #
  if [ X${PATH_monitoring_file} != X"" ] ; then
    IGCM_debug_Print 1 "Monitoring file used : ${PATH_monitoring_file}"
    IGCM_debug_Print 1 "Determine which frequency of time series to be used."

    FreqTS=$( grep FreqTS ${PATH_monitoring_file} | grep -v \# | awk -F "=" '{print $2}' )
    if [ X${FreqTS} = X ] ; then
      # Default frequency is MO
      FreqTS=MO
    fi

    IGCM_debug_Print 1 "Times series frequency to be used is ${FreqTS}"
    IGCM_debug_Print 1 "Determine which files we need."
    . monitoring01 -l2 --listcommand 'IGCM_sys_RshArchive_NoError ls' ${PATH_monitoring_file} ${R_SAVE}/${comp}/Analyse/TS_${FreqTS}
    liste_file_monitoring=$( . monitoring01 -q -l2 --listcommand 'IGCM_sys_RshArchive_NoError ls' ${PATH_monitoring_file} ${R_SAVE}/${comp}/Analyse/TS_${FreqTS} )
  fi
  #
  if [ ! "X${liste_file_monitoring}" = X ] ; then
    IGCM_sys_Get /l liste_file_monitoring ${RUN_DIR}
    IGCM_debug_Print 1 "monitoring01 -c ${CARD_DIR} -p ${comp} --time -t \"${config_UserChoices_JobName} monitoring\" -o ${RUN_DIR}/MONITORING ${PATH_monitoring_file} ."
    IGCM_debug_Print 1 "monitoring01 starts ................................................."
    monitoring01 -c ${CARD_DIR} -p ${comp} --time -t "${config_UserChoices_JobName} monitoring" -o ${RUN_DIR}/MONITORING ${PATH_monitoring_file} .
  else
    IGCM_debug_Print 1 "No time series detected by this command :"
    IGCM_debug_Print 1 "monitoring01 -l2 --listcommand 'IGCM_sys_RshArchive_NoError ls' ${PATH_monitoring_file} ${R_SAVE}/${comp}/Analyse/TS_${FreqTS}"
    . monitoring01 -l2 --listcommand 'IGCM_sys_RshArchive_NoError ls' ${PATH_monitoring_file} ${R_SAVE}/${comp}/Analyse/TS_${FreqTS}
  fi

  # Now do cleaning before starting with next component
  rm -f ${RUN_DIR}/*nc

done

# IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII

# Save files
IGCM_sys_Put_Dir MONITORING ${R_FIGR}

# Dods copy
if [ X${config_Post_DodsCopy} = XTRUE ]  ; then
  IGCM_sys_Put_Dods MONITORING
fi

# Clean RUN_DIR_PATH (necessary for cesium and titane only)
IGCM_sys_RmRunDir -Rf ${RUN_DIR_PATH}

# ------------------------------------------------------------------
# Finalize BigBrother to inform that the jobs end
# ------------------------------------------------------------------
IGCM_debug_BigBro_Finalize
