#!/bin/bash
# AI mai 2020
# A REFAIRE PROPREMENT 
# A NETTOYER, ADAPTER AUX AUTRES MACHINES

###########################################################################
###########################################################################
# Traitement d'une serie d'experiences se trouvant sur le repertoire
# $ROOTSTORAGE/$EXPNAME
# L'organisation des fichiers suit celle de libIGCM
# Une simulation sera par exemple stokÃee sur 
# $ROOTSTORAGE/$EXPNAME/${run}/ATM/Analyse/${run}_SE_1980_1986_1M_hitsmth.nc
#                             /ATLAS/Analyse/SE/${run}_base
# le script cree eventuellement les atlas si ils n'existent pas
# calcule les valeurs inglobales (flux au sommet, prÃecip ...)
# publie l'ensemble sur DODS
# et cree un fichier html pointant vers cette arborescence dods.
###########################################################################
###########################################################################
module load ferret

#set -x


comp=COMP

helptext="
        --help Ce manuel
        --run Nom de la simulation
        --id  Nom du repertoire contenant la simuation a partir de $STORAGE
        --wd  Nom du repetoire temporaire
        --origwww Au cas ou les simulations viennent d ailleurs
"

while test -n "${1}"; do
  case "${1}" in
        --help) echo "$helptext";
            exit 0;;
        --comp) comp="${2}"
                 shift;;
        --id) CONFIGNAME="${2}"
                 shift;;
        --wd) ROOTWORK="${2}"
                 shift;;
        --origwww) ROOTWEBORIG="${2}"
                 shift;;
        *) echo "make_se.sh: argument non reconnu ${1}"; exit 1;;
  esac
  shift
done

local=`pwd -P`

login=`whoami`
hostname=`hostname`
if [ ${hostname:0:5} = cicla ] ; then
DODSDIR=/thredds/ipsl
HTML=http://vesg.ipsl.upmc.fr/thredds/fileServer/IPSLFS/$login/lmdz/MultiSimu/$comp
machine=ciclad
fi
if [ ${hostname:0:5} = camel ] ; then
DODSDIR=/thredds/ipsl
fi
if [ ${hostname:0:5} = irene ] ; then
DODSDIR=
fi
if [ ${hostname:0:5} = jean- ] ; then
DODSDIR=
fi

tmpdir=$DODSDIR/$login/lmdz
EXPNAME=B96x95x39/V20090611.dev/
ROOTWORK=$tmpdir
ROOTWEBORIG=""
EXPNAME=IGCM_OUT/$CONFIGNAME/DEVT/clim

STORAGE=$ARCHIVE
put=mfput
ROOTWEBatlas=http://dods.idris.fr/$LOGNAME/$EXPNAME
HTML_D=$ROOTSTORAGE/HTML

if [ "$machine" = "ciclad" ] ; then
EXPNAME=NPV5LRL79
put=cp
CICLAD=$DODSDIR/$login/lmdz
ARCHIVE=$CICLAD/STORE
workdir=$CICLAD/WORK
STORAGE=$CICLAD
ROOTWEBatlas=http://vesg.ipsl.upmc.fr/thredds/fileServer/IPSLFS/$login/lmdz/STORE/$EXPNAME
MULTIDIR=$DODSDIR/$login/lmdz/MultiSimu
COMP_D=$MULTIDIR/$comp
DEF_FILE=$COMP_D/def.txt
HTML_D=$COMP_D
runstxt=$local/runs.txt
fi


ROOTSTORAGE=$ARCHIVE/$EXPNAME
ROOTDODS=DODS/pub/$LOGNAME/$CONFIGNAME
ROOTWEB="http://dodsp.idris.fr/$LOGNAME/$EXPNAME"
ROOTWEB_PRODout=https://vesg.ipsl.upmc.fr/thredds/catalog/store_thredds/aidel/LMDZOR/DEVT/clim
STOREWEB_PROD=http://esgf.extra.cea.fr/thredds/catalog/store_thredds/aidel/IGCM_OUT/LMDZOR/DEVT/clim
STOREWEB_PRODold=http://esgf.extra.cea.fr/thredds/catalog/store/aidel/IGCM_OUT/LMDZOR/DEVT/clim
if [ "$ROOTWEBORIG" = "" ] ; then
ROOTWEBORIG=ROOTWEBlibigcm
fi

echo ROOTSTORAGE $ROOTSTORAGE ROOTWEB $ROOTWEB
 
glob=1

# Version Abderrahmane/centres de caclcul
listevar="bils fnet tops topl topl0 crfsw crflw crfnet eva pr prw "
# Version ciclad multi-atlas
listevar="bils rt   rst  rlut rlutcs  crest crelt cret eva pr prw "
listevalvar="7.097 0.7823 240.4 239.6 269.4 -47.05 29.84 -17.21 3.415 2.61 27.46 "


###########################################################################
# CREATION DE L'ENTETE DU FICHIER html
###########################################################################

# Horrible astuce pour controler a peu pres la longueur des chaines
# de caractere pour la description des simus 
longn=`wc -lc $DEF_FILE | awk ' { print int ( $2 / $1 / 2 ) } '`
longc="" ; i=0 ; while [ $i != $longn ] ; do (( i = $i + 1 )) ; longc="$longc"_ ; done

if [ ! -d $STORAGE/HTML ] ; then mkdir -p $STORAGE/HTML ; fi
htmlfile=$STORAGE/HTML/tmp.html   ; rm -f $htmlfile ; touch $htmlfile
errfile=$STORAGE/HTML/tmphtml$$.err ; rm -f $errfile  ; touch $errfile
D_work=$ROOTWORK/tmp_makehtml$$ ; rm -rf $D_work ; mkdir -p $D_work
emptyelt='<td> - </td>'
cat <<eod>| $htmlfile
<table cellpadding="2" cellspacing="2" border="1"
 style="text-align: left; width: 100px; margin-left: auto;
margin-right: auto;">
<tr>
<td><a href="$HTML/def.txt"> RUN (link to outputs)  </a></td>
<td> Atlas YEAR</td>
<td> Atlas --DJF-- </td>
<td> Atlas --JJA-- </td>
<td> Description of the simulation $longc </td>
<td> Period </td>
<td> Name (link to parameters) </td>
eod

if [ $glob = 1 ] ; then
   for var in $listevar ; do
      echo '<td> '$var' </td>' >> $htmlfile
   done
fi

################CLIMATOS##################################################
echo '<tr>' >> $htmlfile
echo "<td> CLIMATOS </td>" >> $htmlfile
echo "<td>        </td>" >> $htmlfile
echo "<td>        </td>" >> $htmlfile
echo "<td>        </td>" >> $htmlfile
echo "<td>        </td>" >> $htmlfile
echo "<td>        </td>" >> $htmlfile
echo "<td>        </td>" >> $htmlfile
if [ $glob = 1 ] ; then
   for var in $listevalvar ; do
      echo '<td> '$var' </td>' >> $htmlfile
   done
fi
echo '<tr>' >> $htmlfile

lc=`wc -l $DEF_FILE | awk ' { print $1 } '`
ll=1
###########################################################################
# DEBUT DE LA BOUCLE SUR LES SIMULATIONS
while [ $ll -le $lc ] ; do
#for sim in `awk ' {print $1} ' $DEF_FILE` ; do
    line=`sed -n -e ${ll}p $DEF_FILE`
    sim=`echo $line | awk ' { print $1 } '`
    simdir=`grep -w "^$sim "  $runstxt | awk ' { print $2 } '`
    run=`basename $simdir `
    years=`echo $line | awk ' { print $2 } '`
    yearsb=`echo $years | sed -e 's/_/-/'`
    echo run $run
    echo '<tr>' >> $htmlfile
###########################################################################



NCFILE=${run}_SE_${years}_1M_histmth.nc

#--------------------------------------------------------------------------
# Liens vers les fichiers, monitoring et atlas
#--------------------------------------------------------------------------
    echo "<td><a href=\"$ROOTWEB_PRODout/"$run"/catalog.html\"> "$sim" </a></td>" >> $htmlfile

D_SE=$run/ATM/Analyse/SE

echo OK0
#    if [ -f "$ROOTSTORAGE/$D_SE/$NCFILE" ] ; then
     if [ 1 = 1 ] ; then

            for SEAS in YEAR DJF JJA ; do
               echo '<td>' >> $htmlfile
               for PROJ in GLOB NH SH ; do
                 atlas=index_${PROJ}_${SEAS}_${run}_$years.html
                 echo Chemin atlas
                 echo $COMP_D/ATLAS/$atlas
                 if [ -f $COMP_D/ATLAS/$atlas ] ; then
                     atlasf=$COMP_D/ATLAS/$atlas
                 else # Ancienne version des scripts d'atlas :
                     atlasf=$ROOTSTORAGE/$run/ATLAS/SE_$years/ATM/$atlas
                 fi
# ATTENTION A REFAIRE EN FONCTION DE LA MACHINE
                 atlas_html=`echo $atlasf | sed -e 's:/thredds/ipsl/:http\://vesg.ipsl.upmc.fr/thredds/fileServer/IPSLFS/:'`
                 echo atlas_html $atlas_html
                 echo atlasf $atlasf
                 if [ -f $atlasf ] ; then
                    echo "<a href=\"$atlas_html\"> ${PROJ:0:1} </a>"
                    echo "<a href=\"$atlas_html\"> ${PROJ:0:1} </a>" >> $htmlfile
                 else
                    echo "-" >> $htmlfile
                    echo Le fichier $atlas_html n\'existe pas
                 fi
               done
               echo '</td>' >> $htmlfile
            done


#--------------------------------------------------------------------------
    else # Cas ou le fichier histmth.nc n est pas present
#--------------------------------------------------------------------------
        echo Le fichier $ROOTSTORAGE/"$run"/$D_SE/$NCFILE n\'existe pas >> $errfile
        for i in 1 2 3 ; do
            echo "$emptyelt" >> $htmlfile
        done
    fi

# Parametres testes par rapport a la simulation de Ref
    grep "^$sim "  $DEF_FILE | grep $years | sed -e 's/'$years'//' -e 's/'$sim'/<td>/' -e 's/$/<\/td>/' >> $htmlfile
    echo '<td> '$years' </td>' >> $htmlfile

    echo "<td><a href=\"$ROOTWEB_PROD/"$run"/catalog.html\"> "$sim" </a></td>" >> $htmlfile
#--------------------------------------------------------------------------
# Parametres globaux
#--------------------------------------------------------------------------
echo OK0
   if [ $glob = 1 ] ; then
     echo OK GGGGGGGGGGGGG $glob
     listeval=""
     echo LISTEVAR $listevar
     for var in $listevar ; do
     echo $ROOTWORK/VLR/YEAR/${sim}_$years/METRICS/glob
          if [ -f "$ROOTWORK/VLR/YEAR/${sim}_$years/METRICS/glob" ] ; then 
              val=`grep "^$var " $ROOTWORK/VLR/YEAR/${sim}_$years/METRICS/glob | awk ' { print $2 }' `
            echo $val
          else
              val=.
          fi
          listeval="$listeval <td> $val </td>"
     done
     echo $listeval
     echo $listeval >> $htmlfile
   fi # glob
echo LISTEVAL $listeval

###########################################################################
# FIN DE LA BOUCLE SUR LES SIMULATIONS
###########################################################################
    echo '</tr>' >> $htmlfile
    (( ll = $ll + 1 ))
done
echo $htmlfile

#############################################################################
# Traitement eventuel des comparaisons
#############################################################################

echo '<tr>' >> $htmlfile

if [ -f cmp.liste ] ; then

 for cmp in `awk ' { print $1 } ' cmp.liste` ; do

  descr=`grep "$cmp " cmp.liste | awk ' { print $2 } '`

# Rajout des courbes de comparaison entre simulations
 echo '<tr>' >> $htmlfile
    echo "<td> $cmp </td>" >> $htmlfile
    echo "<td><a href=\"$ROOTWEB/$cmp/ATLAS\"> X </a></td>" >> $htmlfile
    echo "<td> X </td>" >> $htmlfile
    echo "<td> X </td>" >> $htmlfile
    echo "<td><a href=\"$ROOTWEB/$cmp/MoyZon/$years/catalog.html\"> "X" </a></td>" >> $htmlfile
    echo "<td><a href=\"$ROOTWEB/$cmp/CRF/$years/catalog.html\"> "X" </a></td>" >> $htmlfile
    echo "<td> X  </td>" >> $htmlfile
    echo "<td> X  </td>" >> $htmlfile
    echo "<td> X  </td>" >> $htmlfile
    echo "<td> X  </td>" >> $htmlfile
    echo "<td> X  </td>" >> $htmlfile
    echo "<td> $descr </td>" >> $htmlfile
  echo '</tr>' >> $htmlfile

done
fi

echo '</table>' >> $htmlfile
###########################################################################

mkdir -p $HTML_D
$put $htmlfile $HTML_D/Table_simulations_${comp}.html
echo $put $htmlfile $HTML_D/Table_simulations_${comp}.html

