#-Q- curie ######################
#-Q- curie ## CURIE   TGCC/CEA ##
#-Q- curie ######################
#-Q- curie #MSUB -r PACKRESTART    # Nom du job
#-Q- curie #MSUB -o PACKRESTART.out_%I
#-Q- curie #MSUB -e PACKRESTART.out_%I
#-Q- curie #MSUB -n 1              # Reservation du processus
#-Q- curie #MSUB -T 7200          # 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 PACKRESTART    # Job name
#-Q- irene #MSUB -o PACKRESTART.out_%I
#-Q- irene #MSUB -e PACKRESTART.out_%I
#-Q- irene #MSUB -n 1              # Number of cores
#-Q- irene #MSUB -T 7200           # 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-ROME  TGCC/CEA ##
#-Q- irene-amd ##########################
#-Q- irene-amd #MSUB -r PACKRESTART     # Job name
#-Q- irene-amd #MSUB -o PACKRESTART.out_%I
#-Q- irene-amd #MSUB -e PACKRESTART.out_%I
#-Q- irene-amd #MSUB -n 1              # Number of cores
#-Q- irene-amd #MSUB -T 7200          # 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=PACKRESTART         # Job Name
#-Q- jeanzay #SBATCH --output=PACKRESTART.out_%J    # standard output
#-Q- jeanzay #SBATCH --error=PACKRESTART.out_%J     # error output
#-Q- jeanzay #SBATCH -N  1                        # Number of core
#-Q- jeanzay #SBATCH --partition=prepost          # Post-processing partition
#-Q- jeanzay #SBATCH --time=10:00:00                # Wall clock limit (seconds)
#-Q- jeanzay #SBATCH --account ::default_project::@cpu
#-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 = 10:00:00
#-Q- ada # Nom du travail LoadLeveler
#-Q- ada # @ job_name   = PACKRESTART
#-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 ; $MODIPSL ; $libIGCM ; $libIGCM_SX ; $POST_DIR ; $Script_Post_Output ; $SUBMIT_DIR ; $PeriodDateBegin ; $DateBegin ; $DateEnd ; $PeriodPack ; $StandAlone ; $MASTER ; wall_clock_limit=$(wall_clock_limit)
#-Q- ada # @ queue
#-Q- lxiv8 ######################
#-Q- lxiv8 ## OBELIX      LSCE ##
#-Q- lxiv8 ######################
#-Q- lxiv8 #PBS -N PACKRESTART
#-Q- lxiv8 #PBS -m a
#-Q- lxiv8 #PBS -j oe
#-Q- lxiv8 #PBS -q medium
#-Q- lxiv8 #PBS -o PACKRESTART.$$
#-Q- lxiv8 #PBS -S /bin/ksh
#-Q- ifort_CICLAD ######################
#-Q- ifort_CICLAD ##   CICLAD    IPSL ##
#-Q- ifort_CICLAD ######################
#-Q- ifort_CICLAD #PBS -N PACKRESTART
#-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

#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 (ulam 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- $hostname of the MASTER job when SUBMIT_DIR is not visible on postprocessing computer.
MASTER=${MASTER:=ada|curie}

#D- Flag to determine begin date for restart pack
#D- Default : value from AA_job if any
DateBegin=${DateBegin:=20000101}

#D- Flag to determine end date for restart pack
#D- Default : value from AA_job if any
DateEnd=${DateEnd:=20691231}

#D- Flag to determine pack period
#D- Default : value from AA_job if any
PeriodPack=${PeriodPack:=10Y}

#D- Uncomment to run interactively
#D- For testing purpose, will be remove
#SUBMIT_DIR=${PWD}
#RUN_DIR_PATH=${SCRATCHDIR}/Pack_Test

#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- Keep following comments for now. Will be remove.

#on veut archiver les fichiers restart
#Dans le cadre du demenagement ils seront renommes
#ATM/Restart/****.nc
#OCE/Restart/****.nc
#...
#sous la forme
#RESTART/ATM_****.nc
#RESTART/OCE_****.nc
#Attention de bien conserver les dates d'origines
#
#Dans le cadre de la production nouvelle chaine
#ils auront directement le bon nom
#
#On veut egalement que l'archive soit par periode de temps
# cette periode est definie par la taille du pack donc connue
# en entree du script (1M, 1Y, 5Y, 10Y etc...)
#
# $1= PATH/config_card d'une simulation avec
# TagName/JobName/ExperimentName/SpaceName/DateBegin/DateEnd
# $2=PeriodPack en M/m ou Y/y

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

. ${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
. ${libIGCM}/libIGCM_post/libIGCM_post.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_PATH}
    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

#==================================
# Test and set up directories
#==================================
IGCM_sys_TestDirArchive ${R_SAVE}
[ $? != 0 ] && IGCM_debug_Exit "IGCM_sys_TestDirArchive"

STORE_RESTART=${R_SAVE}/RESTART
IGCM_sys_MkdirArchive ${STORE_RESTART}

# Switch to script variables meaning (try to be compatible with ipsl_pack TGCC moving procedure)
JobName=${config_UserChoices_JobName}
echo $JobName $R_BUFR $DateBegin $DateEnd

# Clear txt file lists
rm -f ${RUN_DIR}/liste_restart_files.txt
rm -f ${RUN_DIR}/new_liste_restart_files.txt
rm -f ${RUN_DIR}/liste_pack_*.txt
rm -f ${RUN_DIR}/liste_pack_light_*.txt

# Create sorted restart list to work with
find ${R_BUFR}/*/Restart -name "*.*" | sort >> ${RUN_DIR}/liste_restart_files.txt

# Rename restart files we will work with using symlinks
#gawk -F/ '{dest_name=$(NF-2)("_") $(NF); system("cp --preserve " $0 " "dest_name)}' ${RUN_DIR}/liste_restart_files.txt
gawk -F/ '{dest_name=$(NF-2)("_") $(NF); system("ln -s " $0 " "dest_name)}' ${RUN_DIR}/liste_restart_files.txt

# List renamed restart files
find ${RUN_DIR} -maxdepth 1 -mindepth 1 -name "???_*${JobName}*" -ls | sort -k 11 > ${RUN_DIR}/new_liste_restart_files.txt

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

# Init loop
date_begin_pack=${DateBegin}
date_end_simulation=${DateEnd}
number_pack=1

IGCM_debug_PrintVariables 3 date_begin_pack
IGCM_debug_PrintVariables 3 date_end_simulation

# last restart of the previous period : to be deleted
typeset date_end_previous
date_end_previous=$( IGCM_date_AddDaysToGregorianDate ${date_begin_pack} -1 )

while [ ${date_begin_pack} -le ${date_end_simulation} ] ; do

  IGCM_debug_PrintVariables 3 number_pack

  DaysTemp=$( IGCM_date_DaysInCurrentPeriod ${date_begin_pack} ${PeriodPack} )
  date_end_pack=$( IGCM_date_AddDaysToGregorianDate ${date_begin_pack} $(( ${DaysTemp} - 1 )) )

  for file in $( gawk '{print $11}' ${RUN_DIR}/new_liste_restart_files.txt ); do
    extract_date_file=$( echo ${file}  | sed -e "s/.*${JobName}_//" )
    date_file=$( echo ${extract_date_file} | sed 's/\([0-9]\{8\}\)_.*$/\1/g' )
    # warning demenagement. delete last restart of the previous pack
    [  ${date_file} -eq ${date_end_previous} ] && echo $( readlink ${file} ) >> ${RUN_DIR}/liste_remove_pack_${date_begin_pack}_${date_end_pack}.txt
    # echo pack number ${number_pack}  ${date_file} ${date_begin_pack} ${date_end_pack}
    if [ ${date_file} -le ${date_end_pack} ] && [ ${date_file} -ge ${date_begin_pack} ] ; then
      echo $( basename ${file} ) >> ${RUN_DIR}/liste_pack_${date_begin_pack}_${date_end_pack}.txt
      # warning demenagement. do not delete last restart of this pack
      [ ${date_file} -eq ${date_end_pack} ] || echo $( readlink ${file} ) >> ${RUN_DIR}/liste_remove_pack_${date_begin_pack}_${date_end_pack}.txt
    fi
    # light pack list of restarts files that will be used
    if [ X${config_Post_LightRestartPack} = XTRUE ] ; then
      if [ ${date_file} -le ${date_end_pack} ] && [ ${date_file} -ge ${PeriodDateBegin} ] ; then
        echo $( basename ${file} ) >> ${RUN_DIR}/liste_pack_light_${date_begin_pack}_${date_end_pack}.txt
      fi
    fi
  done

  # Create tar files
  IGCM_debug_Print 1 "Tar ongoing"
  if [ X${config_Post_LightRestartPack} = XTRUE ] ; then
    tar -cvf ${JobName}_${date_begin_pack}_${date_end_pack}_restart.tar --dereference --files-from ${RUN_DIR}/liste_pack_light_${date_begin_pack}_${date_end_pack}.txt
  else
    tar -cvf ${JobName}_${date_begin_pack}_${date_end_pack}_restart.tar --dereference --files-from ${RUN_DIR}/liste_pack_${date_begin_pack}_${date_end_pack}.txt
  fi
  # Test return code of tar
  [ $? != 0 ] && IGCM_debug_Exit "tar failed in pack_restart job"
  # Save it
  IGCM_sys_Put_Out ${JobName}_${date_begin_pack}_${date_end_pack}_restart.tar ${STORE_RESTART}
  # Clean it
  IGCM_sys_Rm ${JobName}_${date_begin_pack}_${date_end_pack}_restart.tar
  # ------------------------------------------------------------------
  # Test if all was right before proceeding cleaning
  # ------------------------------------------------------------------
  IGCM_debug_Verif_Exit
  # Clean links
  cat ${RUN_DIR}/liste_pack_${date_begin_pack}_${date_end_pack}.txt | xargs rm
  # Clean files links pointed to
  cat ${RUN_DIR}/liste_remove_pack_${date_begin_pack}_${date_end_pack}.txt | xargs rm
  # Save the list of files that has been pack (tar)
  #mv ${RUN_DIR}/liste_pack_${date_begin_pack}_${date_end_pack}.txt ${STORE_RESTART}
  IGCM_debug_Print 1 "Tar and cleaning done"

  (( number_pack = number_pack + 1 ))

  # Add 1 day to date_end_pack to have the new date_begin_pack
  date_begin_pack=$( IGCM_date_AddDaysToGregorianDate ${date_end_pack} 1 )

done

# 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

date
