#!/bin/bash

comp=$1
ref=$2

login=`whoami`
DODSDIR=/thredds/ipsl

echo DODSDIR : $DODSDIR
MAIN_SE=$DODSDIR/$login/lmdz/SE
TS_DA=$DODSDIR/$login/lmdz/TS_DA
TS_MO=$DODSDIR/$login/lmdz/TS_MO
MULTIDIR=$DODSDIR/$login/lmdz/MultiSimu

COMP_D=$MULTIDIR/$comp

if [ 1 == 0 ]; then
if [ $dataref = 1 ]; then
ref=OBS
elif [ $dataref = 0 ]; then
ref=`head -1 ${COMP_D}/def.txt | awk ' { print $1"_"$2 } '`
fi
fi

echo dataref=$dataref
echo ref=$ref

DEF_FILE=$COMP_D/def.txt ; if [ ! -f $DEF_FILE ] ; then echo renseigner $DEF_FILE ; exit ; fi
RUNS=""
RUNS=`awk ' {print $1"_"$2 } ' $DEF_FILE`

echo $RUNS

natlas=`wc -l $COMP_D/atlas-def | awk ' { print $1 } '`
echo $natlas

for sim in $RUNS; do

 il=1
 if [ ! -f $COMP_D/atlas-def ] ; then
    echo Definir les atlas a construire dans $COMP_D/atlas-def
    echo Example :
    cat $COMP_D/../CMIP5to6/atlas-def
 fi
 while [ $il -le $natlas ] ; do
    line=`sed -n -e ${il}p $COMP_D/atlas-def`
    seas=`echo $line | awk ' { print $1 } '`
    proj=`echo $line | awk ' { print $2 } '`
    vars=`echo $line | awk ' { print $3 } '`
    varg=`echo $vars | sed -e 's/,/ /g'`

listvar=""
for var in $varg; do

case $var in
          tas) titre='2M Temperature' ;;
          pr) titre='Precipitation' ;;
          crest) titre='CRE SW TOA' ;;
          crelt) titre='CRE LW TOA' ;;
          crett) titre='CRE Net TOA' ;;
          rtt) titre='Rad. Net TOA' ;;
          rstt) titre='Rad. SW TOA' ;;
          rlut) titre='Rad. LW TOA' ;;
          prw) titre='Precipitable Water' ;;
          rsds) titre='Rad. SW Down Sfce' ;;
          hfls) titre='Latent heat flux' ;;
          ta) titre='Air Temperature' ;;
          ua) titre='Zonal wind' ;;
          hur) titre='Relative Humidity' ;;
          hurs) titre='Surface Relative Humidity' ;;
          psl) titre='Sea level pressure' ;;
          albs) titre='Surface albedo' ;;
          *) titre=${var} ;;
esac

if [ "${titre}" == ${var} ]; then 
 echo WARNING: la variable $var n est pas presente dans make_index_html.sh
 echo WARNING: Ajouter-la avec un titre dans le case ci-dessus et
 echo WARNING: relancer job_multi.sh en activant la partie html uniquement!
fi

cp var_html.html "${var}"_html.html

#echo var=$var"endvar" titre=$titre"endtitre"
sed -i -e "s/VAR/${var}/g" ${var}_html.html
sed -i -e "s/TITRE/${titre}/g" ${var}_html.html
sed -i -e "s/SIMULATION/${sim}/g" ${var}_html.html
sed -i -e "s/LOGIN/"${login}"/g" ${var}_html.html
sed -i -e "s/SEASON/"${seas}"/g" ${var}_html.html
sed -i -e "s/DREF/"${ref}"/g" ${var}_html.html
sed -i -e "s/REGION/"${proj}"/g" ${var}_html.html
listvar="$listvar ${var}_html.html"
done
cat entete_html.html ${listvar} suff_html.html > ${COMP_D}/ATLAS/index_${proj}_${seas}_${sim}.html
echo \rm ${listvar}
\rm ${listvar}
(( il = $il + 1 ))
done

done


exit
