#!/bin/bash

# But : trouver la taille ideale de pack pour une simulation donnee
# on part sur une base de 10 ans et on augmente par 0.5 ou on divise 
# par 2 suivant un critère de taille
# on passe en revue tous les types de fichiers d'Output et on conserve
# la taille de pack la plus petite (hors HF) 

# $1= PATH/config_card d'une simulation avec 
# TagName/JobName/ExperimentName/SpaceName/DateBegin/DateEnd/PATH_SIMUL

# pour commencer on travaille avec le fichier information_dmnfs
#/cscratch/cont003/p86mart/FROM_CCRT_INFORMATIONS_DMNFS/information_dmnfs_2011-09-21

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

# ----
export JOB_DIR=${JOB_DIR:-${PWD}}
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
DEM_log -0 "Demmarrage de ${SCRIPT_NAME}"
cd ${JOB_DIR}
# ----

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} )

DEM_state=$( DEM_read_state ${IGCM_DEM}/config_card.liste ${config_card} )
if [[ "${DEM_state}" != "ListToBeDone" ]] ; then
    DEM_log -0 "Attention : Etat incorrect dans ${IGCM_DEM}/config_card.liste"
    exit -1
fi

DEM_write_state ${IGCM_DEM}/config_card.liste ${config_card} FindSizePackRunning

# Periodicite du pack (20 ans par defaut) 
period_pack=20Y
periodpackinyear=$( echo ${period_pack} | sed -e 's/[yY]//' ) 

# Taille max et min que devra avoir un pack en octet (20Go - 70Go) 
size_pack_max=70000000000
size_pack_min=20000000000

SIMUL=${PATH_SIMUL_FULL}/

# Nettoyons les tests precedents .... 
rm -f ${IGCM_DEM_SIMU}/info_Output.txt
rm -f ${IGCM_DEM_SIMU}/info_name_file.txt

# 1- Trouver tous les repertoires d'Output
DEM_log -1 "Recherche des repertoires Output"

#grep ${SIMUL} ${LISTE_DMNFS} > ${IGCM_TMP}/${$}.info_tmp.txt
#grep "/Output/"  ${IGCM_TMP}/${$}.info_tmp.txt >  ${IGCM_TMP}/${$}.info_tmp_2.txt
#awk '{print $(NF-2) " " $(NF-1)}' ${IGCM_TMP}/${$}.info_tmp_2.txt > ${IGCM_DEM_SIMU}/info_Output.txt

[[ "${clean_tmp}" = "yes" ]] && rm -f   ${IGCM_TMP}/${$}.info_tmp.txt  ${IGCM_TMP}/${$}.info_tmp_2.txt

# 2- Trouver la liste des noms des fichiers d'Output
DEM_log -1 "Recherche des noms de fichiers Output"

sed -e "s%.*_\([0-9]\{8\}\)_\([0-9]\{8\}\)_%%" ${IGCM_DEM_SIMU}/liste_output_files_config.txt  | awk '/.nc/{print $0}'  >  ${IGCM_TMP}/${$}.info_tmp.txt

#on enleve si des fichiers ne repondent pas au critere et sont donc encore en /
cat ${IGCM_TMP}/${$}.info_tmp.txt | grep -v "/" > ${IGCM_TMP}/${$}.info_tmp_bis.txt


# On enleve mesh_mask qui est un cas particulier a traiter ulterieurement
sed '/mesh_mask/d' ${IGCM_TMP}/${$}.info_tmp_bis.txt >  ${IGCM_TMP}/${$}.info_tmp_2.txt

# On retire les doublons de la liste précédent
awk '{if (x[$0] != "") next ; print $0 ; x[$0]=$0}' <  ${IGCM_TMP}/${$}.info_tmp_2.txt >> ${IGCM_DEM_SIMU}/info_name_file.txt
[[ "${clean_tmp}" = "yes" ]] && rm -f  ${IGCM_TMP}/${$}.info_tmp.txt ${IGCM_TMP}/${$}.info_tmp_2.txt


#!!!# Reduction de la taille du probleme pour test
# grep 1M_cpl_atm.nc  ${IGCM_DEM_SIMU}/info_name_file.txt >  ${IGCM_DEM_SIMU}/info_name_file.txt.tmp
# grep 1M_grid_T.nc  ${IGCM_DEM_SIMU}/info_name_file.txt >>  ${IGCM_DEM_SIMU}/info_name_file.txt.tmp
# mv ${IGCM_DEM_SIMU}/info_name_file.txt.tmp ${IGCM_DEM_SIMU}/info_name_file.txt

# On cree la liste des fichiers pour chaque type_file
DEM_log -1 "Creation de la liste des fichiers"

for type_file in `awk '{print $0}' ${IGCM_DEM_SIMU}/info_name_file.txt`
do 
#for type_file in 1D_cpl_atm.nc ; do
    DEM_log -1 "Traitement type de fichier = ${type_file}"
    grep ${type_file} ${IGCM_DEM_SIMU}/liste_output_files_config.txt >  ${IGCM_TMP}/${$}.info_${type_file}.txt
    # cette liste comporte en premiere colonne la taille et en deuxieme le path du fichier
    # on classe la liste par ordre alphabetique des path des fichiers
    sort -k 2  ${IGCM_TMP}/${$}.info_${type_file}.txt >  ${IGCM_TMP}/${$}.tmp_info_${type_file}.txt.tmp
    cp ${IGCM_TMP}/${$}.tmp_info_${type_file}.txt.tmp  ${IGCM_TMP}/${$}.info_${type_file}.txt
    [[ "${clean_tmp}" = "yes" ]] && rm -f ${IGCM_TMP}/${$}.tmp_info_${type_file}.txt.tmp
done


# 3- Maintenant pour chaque type de fichier de sortie nous allons calculer la 
# taille qu'aurait le pack de {periodpackinyear}ans
DEM_log -1 "Debut recherche taille de pack"

# Recherche des dates du premier pack

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

date_begin_pack=${DateBegin}
date_end_simulation=${DateEnd}

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

number_pack=1

# on ne fait le calcul que pour les dix premiers pack (donc 20 * 10 =  200 ans) 
# cela doit donner un echantillon suffisant 
while [[ ${date_begin_pack} -le ${date_end_simulation}  && ${number_pack} -le 10 ]]
do 
    
    month_end_pack=${month_begin_pack}
    year_end_pack=$(( ${year_begin_pack} + ${periodpackinyear} ))
    
    date_end_pack=${year_end_pack}${month_end_pack}01 

    DEM_log -2 "Entree boucle : year_begin_pack month_begin_pack year_end_pack month_end_pack : ${year_begin_pack} ${month_begin_pack} ${year_end_pack} ${month_end_pack}"

    # on travaille pour chaque type de fichiers 
    for type_file in `awk '{print $0}' ${IGCM_DEM_SIMU}/info_name_file.txt`
    do
    #for type_file in 1M_grid_T.nc ; do
	DEM_log -3 ${type_file} ${number_pack}
	taille=0
        #il faut les passer en revue et calculer par tranche de period_pack leur somme
	for file in `awk '{print $2}'  ${IGCM_TMP}/${$}.info_${type_file}.txt` ; do 
            #extraire la date de debut et la date de fin de la periode d'output traitee par le fichier    
            extract_date_file=$( echo ${file}             | sed "s%.*${JobName}_%%"            )
            date_debut=$(        echo ${extract_date_file}| sed 's%\([0-9]\{8\}\)_.*$%\1%g'    )
            date_fin=$(          echo ${extract_date_file}| sed 's%.*_\([0-9]\{8\}\)_.*$%\1%g' )
            if [  ${date_debut} -lt ${date_end_pack} ]
            then 
		if [ ${date_fin} -ge ${date_begin_pack} ]
		then 
		    grep ${file}  ${IGCM_TMP}/${$}.info_${type_file}.txt >>  ${IGCM_TMP}/${$}.info_${type_file}_${number_pack}.txt
	            # on efface le fichier de la liste pour ne pas travailler dessus pour le prochain pack
		    grep -v ${file} ${IGCM_TMP}/${$}.info_${type_file}.txt > ${IGCM_TMP}/${$}.info_${type_file}.txt.tmp
                    cp ${IGCM_TMP}/${$}.info_${type_file}.txt.tmp ${IGCM_TMP}/${$}.info_${type_file}.txt
		    [[ "${clean_tmp}" = "yes" ]] && rm -f ${IGCM_TMP}/${$}.info_${type_file}.txt.tmp
		fi
	    else 
	    # comme la liste est classee par ordre alphabetique --> par ordre croissant des periodes de sorties
	    # des que un fichier n'est plus dans le pack on peut sortir c'est qu'on les a tous. 
		break
            fi
	    
	done
       # on fait la somme par periodpack et par type de fichier de la taille qu'aurait le pack
	awk 'BEGIN {y = 0} {x = $1 ; y = y + x } END{print y}'  ${IGCM_TMP}/${$}.info_${type_file}_${number_pack}.txt >> ${IGCM_TMP}/${$}.size_pack_${type_file}.txt
	[[ "${clean_tmp}" = "yes" ]] && rm -f  ${IGCM_TMP}/${$}.info_${type_file}_${number_pack}.txt
    done
    
    month_begin_pack=${month_end_pack}
    year_begin_pack=${year_end_pack}
    date_begin_pack=${year_begin_pack}${month_begin_pack}01
    
    number_pack=$(( ${number_pack} + 1 ))

    DEM_log -2 "Sortie boucle : year_begin_pack month_begin_pack year_end_pack month_end_pack : ${year_begin_pack} ${month_begin_pack} ${year_end_pack} ${month_end_pack}"

done

# Pour chaque type de fichier on verifie si toutes les tailles sont dans 
# la fourchette size_pack_min / size_pack_max 
# Si une taille est plus petite 
# attention il ne faut pas tenir compte du dernier pack qui peut etre
# inferieur a periodpack

new_period=999999

for type_file in `awk '{print $0}' ${IGCM_DEM_SIMU}/info_name_file.txt`
do 
    nb_line=$(cat ${IGCM_TMP}/${$}.size_pack_${type_file}.txt | wc -l )
    if [ ${nb_line} -gt 1 ] 
    then 
	for taille in `head -n -1  ${IGCM_TMP}/${$}.size_pack_${type_file}.txt`
	do 
            [[ ${taille} -lt ${size_pack_min} ]] && period_tmp=$(( ${size_pack_min} * ${periodpackinyear} / ${taille} ))
            [[ ${taille} -gt ${size_pack_max} ]] && period_tmp=$(( ${size_pack_min} * ${periodpackinyear} / ${taille} ))
            [[ ${taille} -ge ${size_pack_min} && ${taille} -le ${size_pack_max} ]] && period_tmp=${periodpackinyear}
            [[ ${period_tmp} -lt ${new_period} ]] && new_period=${period_tmp}
	done
    else
        # Dans ce cas la il n'y avait pas assez de fichiers pour remplir une periode complete #
        # il faut donc commencer par calculer la taille du pack que l'on a fait #
	yearnewpack=$((    ${year_end}  - ${year_begin}        ))
	monthnewpack=$((   ${month_end} - ${month_begin} + 1   ))
	newpackinmonth=$(( ${yearnewpack}*12 + ${monthnewpack} ))
	newpackinyear=$((  ${newpackinmonth}/12                ))
	[[ ${newpackinyear} -lt 1 ]] && newpackinyear=1
	
	for taille in `head  ${IGCM_TMP}/${$}.size_pack_${type_file}.txt`
	do 
#	  echo ${taille} ${type_file}
            [[ ${taille} -lt ${size_pack_min} ]] && period_tmp=${newpackinyear}
            [[ ${taille} -gt ${size_pack_max} ]] && period_tmp=$(( ${size_pack_min} * ${newpackinyear} / ${taille} ))
            [[ ${taille} -ge ${size_pack_min} && ${taille} -le ${size_pack_max} ]] && period_tmp=${newpackinyear}
            [[ ${period_tmp} -lt ${new_period} ]] && new_period=${period_tmp}
	done
	
    fi 
done

DEM_log -1 "taille=${taille}"
DEM_log -1 "new_period=${new_period}"

# on veut que la taille de pack soit de 1 2 5 10 20 50 ou 100 ans
declare -a liste_period=( 1 2 5 10 20 50 100 )

change=0
for i in 1 2 3 4 5 6 ; do
    if [[ ${new_period} -lt ${liste_period[i]} && ${change} -eq 0 ]]
    then 
	new_period=${liste_period[i-1]}
	change=1
    fi 
done

[[ ${new_period} -gt 100 ]] && new_period=100

[[ "${clean_tmp}" = "yes" ]] && rm -f  ${IGCM_TMP}/${$}.*

echo ${new_period} > ${IGCM_DEM_SIMU}/period_pack.txt
DEM_log -0 "La nouvelle periode de pack est : ${new_period}Y"

DEM_write_state ${IGCM_DEM}/config_card.liste ${config_card} FindSizePackDone

DEM_log -0 "Fin de ${SCRIPT_NAME}"

exit 
