#!/bin/bash


#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/PATH_SIMUL
# $2=period_pack en M/m ou Y/y

config_card=${1}
LISTE_DMNFS=${2}


export JOB_DIR=${JOB_DIR:-${TMP_MIGR_DATA}}
export IGCM_DEM=${IGCM_DEM:-${SCRATCHDIR}/IGCM_DEM}
export IGCM_TMP=${IGCM_TMP:-${IGCM_DEM}/tmp}
mkdir -p ${IGCM_DEM}
mkdir -p ${IGCM_TMP}
clean_tmp=${clean_tmp:-yes}
EXE_DIR=$(dirname ${0})
SCRIPT_NAME=$(basename ${0} )

source ${EXE_DIR}/DEM_utilities.sh

# gpdebug : verif si le present script a ete execute jusqu'au bout #########
MonitoringInfo="${SCRIPT_NAME}-->OK"
simuMonitoring_check "$MonitoringInfo" "$config_card"

DEM_log -0 "Demarrage de ${SCRIPT_NAME}"


#### 0- lecture de config.card 
#### on veut les renseignements suivants : 
#### JobName, PATH_SIMUL, DateBegin et DateEnd
eval $(grep JobName ${config_card}) 
eval $(grep PATH_SIMUL_FULL ${config_card}) 
eval $(grep DateBegin ${config_card}) 
eval $(grep DateEnd ${config_card}) 
eval $(grep IGCM_DEM_SIMU ${config_card})


#### Preparation de l'environnement
# repertoire dans lequel seront renommes les fichiers de restart
STORE_RESTART=$IGCM_DEM_SIMU/RESTART
mkdir -p ${STORE_RESTART}

# repertoire dans lequel nous stockerons les listes de restart a archiver
RESTART_TAR=$IGCM_DEM_SIMU/restart_tar
mkdir -p ${RESTART_TAR}

# lecture de periodpack dans ${IGCM_DEM_SIMU}/period_pack.txt
period_pack=`awk '{print $0} ' ${IGCM_DEM_SIMU}/period_pack.txt`

DEM_log -1 "Period pack = ${period_pack}" 
#### 1- renommer les fichiers ######
DEM_log -1 "Renommer les fichiers de Restart"

cd ${STORE_RESTART}
if [ "x${STORE_RESTART}" != "x" ]
then
rm -rf *
fi

# On les copie sur le scratchdir en changeant le nom et conservant la date
awk '{print $2}' ${IGCM_DEM_SIMU}/liste_restart_files_config.txt > ${IGCM_TMP}/${$}.liste_restart_files.txt
#grep ${PATH_SIMUL_FULL} ${LISTE_DMNFS} | grep Restart | awk '{print $3}' | sed '/^.*Restart$/d' >> ${IGCM_TMP}/${$}.liste_restart_files.txt

  
gawk -F/ '{dest_name=$(NF-2)("_") $(NF); system("ln -s " $0 " "dest_name)}' ${IGCM_TMP}/${$}.liste_restart_files.txt

ls -l ${STORE_RESTART} > ${IGCM_TMP}/${$}.new_liste_restart_files.txt

### 2- creer les listes de fichiers par periode ####
DEM_log -1 "Creation des listes de fichiers par periode"
### 2.1- extraire l'annee et le mois de DateBegin ###
date_begin=${DateBegin}
date_end=${DateEnd}

year_begin=$(echo ${date_begin} | cut -c 1-4 )
month_begin=$(echo ${date_begin} | cut -c 5-6 )
year_end=$(echo ${date_end} | cut -c 1-4 )
month_end=$(echo ${date_end} | cut -c 5-6 )


### 2.2- creation des listes ###
date_begin_pack=${date_begin}
date_end_simulation=${date_end}

month_begin_pack=${month_begin}
year_begin_pack=${year_begin}

number_pack=1

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

DEM_log -1 "On calcule la date de fin du pack "

   month_end_pack=${month_begin_pack}
   year_end_pack=`expr ${year_begin_pack} + ${period_pack}`


   date_end_pack=${year_end_pack}${month_end_pack}01   
   
   if [ "x${ON_IDRIS}" == "xno" ]
   then
       for file in `awk '{print $9}' ${IGCM_TMP}/${$}.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'`

         # DEM_log "date_file = ${date_file}"
	 if [  ${date_file} -lt ${date_end_pack} ]
	 then 
            if [ ${date_file} -ge ${date_begin_pack} ]
            then 
               # DEM_log "${file} ${date_file} dans ${date_begin_pack} ${date_end_pack} "
               echo ${file} >> ${IGCM_TMP}/${$}.liste_pack_restart_${number_pack}.txt
            fi
	 fi  
       done
   else
      for file in `awk '{print $8}' ${IGCM_TMP}/${$}.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'`

         # DEM_log "date_file = ${date_file}"
	 if [  ${date_file} -lt ${date_end_pack} ]
	 then 
            if [ ${date_file} -ge ${date_begin_pack} ]
            then 
               # DEM_log "${file} ${date_file} dans ${date_begin_pack} ${date_end_pack} "
               echo ${file} >> ${IGCM_TMP}/${$}.liste_pack_restart_${number_pack}.txt
            fi
	 fi  
       done  
   fi

#on archive les restart - le nom de l'archive contiendra ${yearbegin}${monthbegin}_${yearend}${monthend} 
# end etant la date du dernier fichier contenu et non pas la premiere date suivant 
DEM_log -1 "Recherche de la date de fin reel pour nommer l'archive "
#On classe par ordre alphabetique les fichiers contenus dans liste_pack_restart 
#la date du dernier fichier donnera la date de fin du pack
   sort ${IGCM_TMP}/${$}.liste_pack_restart_${number_pack}.txt > ${IGCM_TMP}/${$}.liste_pack_restart_${number_pack}.txt.tmp

   first_file=$(head -n 1 ${IGCM_TMP}/${$}.liste_pack_restart_${number_pack}.txt.tmp )
   extract_date_file=$( echo ${first_file}  | sed -e "s/.*${JobName}_//" )
   DateBegin_Restart=$(echo ${extract_date_file}| sed 's%\([0-9]\{8\}\)_.*$%\1%g' )

   last_file=$(tail -n 1 ${IGCM_TMP}/${$}.liste_pack_restart_${number_pack}.txt.tmp )
   extract_date_file=$( echo ${last_file}  | sed -e "s/.*${JobName}_//" )
   DateEnd_Restart=$(   echo ${extract_date_file}| sed 's/\([0-9]\{8\}\)_.*$/\1/g' )
   mv ${IGCM_TMP}/${$}.liste_pack_restart_${number_pack}.txt.tmp ${RESTART_TAR}/${JobName}_restart_${DateBegin_Restart}_${DateEnd_Restart}.list


DEM_log -1 "Passage de la commande Tar pour archiver la liste creee"
#   tar -cf ${JobName}_${date_begin_pack}_${DateEnd_Restart}_restart.tar --dereference  --files-from ${RESTART_TAR}/tar_restart_${date_begin_pack}_${DateEnd_Restart}.list
#   cat  ${RESTART_TAR}/tar_restart_${number_pack}.list | xargs rm 


DEM_log -1 "On definit le datebegin de la  prochaine periode pack"
#on definit la periode pack suivante
   month_begin_pack=${month_end_pack}
   year_begin_pack=${year_end_pack}

   date_begin_pack=${year_begin_pack}${month_begin_pack}01

   number_pack=`expr ${number_pack} + 1`

done


cd ${EXE_DIR}

# gpdebug : le script n'a pas rencontre d'erreur. On l'inscrit dans le fichier de suivi
simuMonitoring_OK "$MonitoringInfo" "$config_card"
