#!/bin/bash

#
# Fonctions utiles pour les scripts de Pack IPSL
#

function DEM_read_state {
# Lire l'état du pack pour une simulation
    local L_CONFIG_FILE=${1}
    local L_CONFIG_CARD=${2}

    local L_OLD_STATE=$( grep ${L_CONFIG_CARD} ${L_CONFIG_FILE} | awk '{print $2}' )
    
    if [ ${?} -eq 0 ] 
    then 
	echo ${L_OLD_STATE}
	return 0
    else
	return 1
    fi
    return 0
}

function DEM_write_state {
# Mettre à jour l'état du pack pour une simulation
    
    local L_CONFIG_FILE=${1}
    local L_CONFIG_CARD=${2}
    local L_NEW_STATE=${3}
    
    local L_OLD_LINE=$( grep ${L_CONFIG_CARD} ${L_CONFIG_FILE} )
    [[ ${?} -eq 0 ]] || ( return 1 ; )
    local L_OLD_STATE=$( echo ${L_OLD_LINE} | awk '{print $2}' )
    [[ ${?} -eq 0 ]] || ( return 1 ; )
    
    L_NEW_LINE="${L_CONFIG_CARD} ${L_NEW_STATE}"

    if [[ ! -f ${L_CONFIG_FILE}.lock ]]
    then 
	touch ${L_CONFIG_FILE}.lock
	sed -i "s%${L_OLD_LINE}%${L_NEW_LINE}%" ${L_CONFIG_FILE}
	rm -f ${L_CONFIG_FILE}.lock
    else
	DEM_log -0 "Erreur. Verrou sur le fichier : ${L_CONFIG_FILE}"
	return 1
    fi
    
    return 0
}

function DEM_min {
# Calcul du minimum d'un nombre quelconque d'entiers
    local l_min=${1} l_xx
  
    for l_xx in ${*:2:${#}}
    do
	[[ ${l_xx} -lt ${l_min} ]] && l_min=${l_xx}
    done
    echo ${l_min}
}

function DEM_max {
# Calcul du maximum d'un nombre quelconque d'entiers
    local l_max=${1} l_xx
  
    for l_xx in ${*:2:${#}}
    do
	[[ ${l_xx} -gt ${l_max} ]] && l_max=${l_xx}
    done
    echo ${l_max}
}

function DEM_log {
# Affichage d'un message sur stdout et dans un fichier de log
# DEM_log [-0|-1|-2|-3] Message
#
    local MESSAGE P_LINE
    LOG_LEV=${LOG_LEV:-3}
    local OPTARG OPTIND L_LOG=1
    local L_DEM_LOG=${DEM_LOG:-dem_log.${$}}

    while getopts 0123 l_name
    do
	case ${l_name} in
            ( 0 )  L_LOG=1 ;;
            ( 1 )  L_LOG=1 ;;
            ( 2 )  L_LOG=2 ;;
	    ( 3 )  L_LOG=3 ;;
	esac
    done
    shift $(( ${OPTIND} - 1 ))

    if [[ ${L_LOG} -le ${LOG_LEV} ]]
    then 
	MESSAGE=${*}
	P_LINE="$(date) - ${MESSAGE}"
	
	echo ${P_LINE}
	echo ${P_LINE} >> ${L_DEM_LOG}
    fi
    return
}
