#!/bin/bash

set -eu

# AFAIRE
# On pourrait gerer le justcheck en creant un repertoire
# avec
#  if recheck
#   resubench=./RESUBENCH$$
#  else
#   resubench=$RESU_D/$datelmdz$rel_svn
#On pourrait ainsi utiliser une fonction independante qui genere les messages
# comme check_version_message



#########################################################################
# Verification de a convergence du modele par rapport aux versions
# precedentes
# + 1+1=2
#########################################################################

function get() {  # fetch lmdz files
  local file=$1

  if [[ -f $file ]]; then return; fi
  # TODO  in the final version:    \rm -f if exists

  if [[ $(whoami) = "lmdz" ]]; then
     ln -sf "/u/lmdz/WWW/$file" .
  else
     wget "https://www.lmd.jussieu.fr/~lmdz/$file"
  fi
}

function set_default_args_val() {
  version_ref="latest"
  resolution="48x36x39"
  parallel="mpi_omp"
  # Option pour le debug du script check_version lui meme qui consiste a ne
  # pars reexecuter l'installation et les simulations mais a simplement
  # refaire les diff sur des simulations existantes.
  justcheck=0 # just compare results not writing of results in RESUBENCH
  tmpdir="/tmp/$(whoami)"; mkdir -p "$tmpdir"
  tmpdir="/home/lmdz/tmp"
  rel_svn=""
  local_d=$(pwd)

  install=1
  rad=rrtm
  check_1D=1
  check_1p1=1
  check_isotopes=1
  check_parallel=1
  check_compile=1
  check_ini=1
  mail_address=lmdz-commit@listes.lmd.ipsl.fr
  MODEL=""
  branche=trunk
}

function read_user_options() {
  while (($# > 0)); do
      case $1 in
          "-h") cat <<fin
    check_version.sh [-h] version [-latest version_ref]
    version is the name of the version of LMDZ to be checked modipsl.version.tar.gz
    version_ref is the version to be compared with.
    Default "latest".
    options:
      -justcheck  : just check results, do not overwrite anything
      -r svn : revision
      -latest latest : latest is the date of the last version tested
      -model_dir : directory where tun run the bench if LMDZ is already installed
fin
            exit 2;;

        "-justcheck") justcheck=1; shift;;
        "-r") rel_svn="$2"; shift; shift;;
        "-latest") version_ref="$2"; shift; shift;;
        "-model_dir") MODEL="$2"; shift; shift;;
        *) version="$1"; shift;;
     esac
  done
}

set_default_args_val
read_user_options "$@"

################################################################################
# Definition des noms des repertoires à comparer
################################################################################

if [[ $MODEL = "" ]]; then
   MODEL=$tmpdir/LMDZ$version$rel_svn
   branche=$(echo "$version" |cut -c 10-)
   datelmdz=$(echo "$version" | cut -d. -f1)
else
   install=0
   if [[ "$(echo "$MODEL" | cut -c1)" != "/" ]]; then MODEL=$(pwd)/$MODEL; fi # MODEL transformed in absolute path if not
   datelmdz=$(date +%Y%m%d)$$
fi

echo "version $version $branche $datelmdz"
RESU_D=~/WWW/RESUBENCH/$branche/defaul
if [[ $justcheck = 0 ]]; then
   resubench="$RESU_D/$datelmdz$rel_svn"
   if [[ -d $resubench ]]; then mv "$resubench" "$resubench$$"; fi
   mkdir -p "$resubench"
fi
latest="$RESU_D/$version_ref"
echo "$latest"

# recuperation de la version a laquelle on compare pour le message final :
comparea=$(ls -ld "$RESU_D/$version_ref" | awk -F/ ' { print $NF } ')
echo "comparea $comparea"

function install_model() {
  local opt_svn

  echo "0. Installation du modele"

  # Edition de install.sh, install.sh avec bench 48x36x19
  if [[ $install = 1 ]]; then
     cd $tmpdir
     if [[ $rel_svn = "" ]]; then opt_svn=""; else opt_svn="-r $rel_svn"; fi
     get "pub/install_lmdz.sh"; chmod +x install_lmdz.sh
     # On install sans les bench pour que les benchs soient faits à la main
     ./install_lmdz.sh -unstable -v "$version" "$opt_svn" -d $resolution -parallel $parallel -veget CMIP6 -bench 0
  fi
}

install_model

################################################################################
echo 1. Sauvegarde du 1D execute automatiquement a l installation
################################################################################

if [ $check_1D = 1 ]; then
   cd $MODEL
   if [ ! -d 1D ]; then $get/pub/1D/1D.tar.gz; tar xvf 1D.tar.gz; fi     # get 1D model
   if [ ! -d 1D/EXEC ]; then mv 1D/EXEC 1D/SAVE_EXEC$$; fi
   cd 1D; sed -e "s:^listecas=.*$:listecas=ARMCU/REF:" run.sh; ./run.sh   # run 1D model
   # Controling outputs for the ARMCU/REF test case -d $dim"
   outf=$MODEL/1D/EXEC/6AL79/ARMCU/REF/restartphy.nc
   if [ -f $outf ]; then
       if [ $justcheck = 0 ]; then
          mkdir -p $resubench/ARMCU/REF
          cp $outf $resubench/ARMCU/REF/
       fi
       cmp -s $outf $latest/ARMCU/REF/restartphy.nc
       if [ $? = 0 ]; then converge1D=U; else converge1D=u; fi
   else
      converge1D=-
   fi
fi


################################################################################
echo DEBUT DES TESTS 3D
################################################################################
BENCH=BENCH$resolution
cd $MODEL/modipsl/mod*/LMD*
LMDZdir=`pwd`
echo LMDZdir $LMDZdir
if [ -d $BENCH ]; then mkdir -p SAVE$$; mv BENCH$resolution SAVE$$; fi
$get/pub/3DBenchs/bench_lmdz_$resolution.tar.gz; tar xvf bench_lmdz_$resolution.tar.gz
cd $BENCH; $get/pub/3DBenchs/BENCHCMIP6.tar.gz .;  tar xvf BENCHCMIP6.tar.gz 
sed -i'' -e "s:VEGET=n:VEGET=y:" config.def
./compilegcm_fcm.sh; ./bench.sh > out.bench 2>&1


if [ -f restartphy.nc ]; then
   if [ ! -f gcm.install ]; then \cp -f gcm.e gcm.install; fi

#########################################################################
echo 3. Verification de la convergence avec la version precedente
echo Physique Standard
#########################################################################

   # Faite soit sur les restart.nc soit sur une exctraction de ps.nc
   # Il est arrive qu'on ait convergence meteo sans identite des restart
   #  (pb d'entete, de traceurs ...)
   # Aide a l'interpretation de resultats problematiques
   #    Les resultats de la simu ancienne physique sont directement 
   #      dans BENC*
   #    Les resultats de la nouvelle physique sont dans SIM1 utilise
   #      pour 1+1=2
   #    Les resultats de la simulation debug sont dans SIMD

   # Ici on se contente d'analyser le bench automatique qui vient de tourner
   if [ $justcheck = 0 ]; then mkdir -p $resubench/$BENCH; fi
   if [ -f restartphy.nc ]; then
       if [ $justcheck = 0 ]; then
           ncks -M -m -h -v ps -O restart.nc $resubench/$BENCH/ps.nc
           cp restart.nc $resubench/$BENCH/restart.nc
       fi
       cmp -s ./restart.nc $latest/$BENCH/restart.nc
      if [ $? = 0 ]; then converge=S; else converge=s; fi
   else
      converge=-
   fi

   #########################################################################
   echo 4. Verification de 1+1=2
   echo Avec la nouvelle physique
   #########################################################################
   # On utilse l'executable du bench de base

   if [ $check_1p1 = 1 ]; then
      \cp -f gcm.install gcm.e
      suf=NPv6.0.14splith
      sed -e 's/VEGET=y/VEGET=n/' config.def_oraer > config.def
      if [ -f physiq.def_$suf ]; then \cp -f physiq.def_$suf physiq.def; fi
      $get/Distrib/unpun.sh
      chmod +x unpun.sh; ./unpun.sh -parallel $parallel
      cmp -s SIM2/ps_end.nc SIM1+1/ps_end.nc
      if [ $? = 0 ]; then
          unpun=OK
      else
          unpun=-
      fi
   fi


# 2016/06/21 : comparaison des versions nouvelles physique (dans SIM1)
   cd $LMDZdir/$BENCH
   if [ -f SIM1/restartphy.nc ]; then
       if [ $justcheck = 0 ]; then
           ncks -M -m -h -v ps -O SIM1/restart.nc $resubench/$BENCH/ps$suf.nc
           cp SIM1/restart.nc $resubench/$BENCH/restart$suf.nc
       fi
       \rm sechiba_out_2.nc sechiba_history.nc sechiba_rest_out.nc
       cmp -s SIM1/restart.nc $latest/$BENCH/restart$suf.nc
      if [ $? = 0 ]; then convergeNP=N; else convergeNP=n; fi
   else
      convergeNP=-
   fi

   #########################################################################
      echo Verification en mode debug + parallele, compile avec makelmdz
   #########################################################################

   cd $LMDZdir/$BENCH
   if [ -f compilegcm.sh -a $check_compile = 1 ]; then
      \rm -f gcm.e
      ./compilegcm.sh -debug
      mkdir SIMD
      cd SIMD
      ln -s ../SIM1/start* ../SIM1/limit* ../SIM1/sechiba_rest_in.nc ../SIM1/aer*nc ../SIM1/*def .
      ../run_local.sh 2 2 ../gcm.e > listing 2>&1
      cd ../
      suf=D
      if [ -f SIMD/restartphy.nc ]; then
          if [ $justcheck = 0 ]; then
              ncks -M -m -h -v ps -O SIMD/restart.nc $resubench/$BENCH/ps$suf.nc
              cp SIMD/restart.nc $resubench/$BENCH/restart$suf.nc
          fi
          cmp -s SIMD/restart.nc $latest/$BENCH/restart$suf.nc
          if [ $? = 0 ]; then convergeD=D; else convergeD=d; fi
      else
         convergeD=-
      fi
   fi

   #########################################################################
      echo Test en fonction du nombre de processeurs
   #########################################################################

echo CHECK $parallel $check_parallel
   if [ "$parallel" = "mpi_omp" -a $check_parallel = 1 ]; then
      mkdir -p $LMDZdir/$BENCH/SIM1_41
      cd $LMDZdir/$BENCH/SIM1_41
      ln -s ../SIM1/start* ../SIM1/limit* ../SIM1/sechiba_rest_in.nc ../SIM1/aer*nc ../SIM1/*def .
      ../run_local.sh 4 1 ../gcm.e > listing
      cd ..
      echo ON EST AVANT LE CMP
      cmp -s SIMD/restart.nc SIM1_41/restart.nc
      if [ $? = 0 ]; then
          if [ "$unpun" = "OK" ]; then
             unpun=OK2
          else
             unpun=-OK
          fi
      else
          unpun=${unpun}-
      fi
   fi

   #########################################################################
      echo Verification des isotopes
   #########################################################################

   if [ $check_isotopes = 1 ]; then
      cd $LMDZdir
      pwd
      $get/pub/3DBenchs/bench_lmdz_iso_48x36x39.tar.gz
      tar xvf bench_lmdz_iso_48x36x39.tar.gz
      cd BENCHiso48x36x39
      ./compile.sh
      exec=../bin/gcm_48x36x39_phylmdiso_${rad}_seq_iso_isoverif.e
      if [ -f $exec ]; then
             $exec > listing 2>&1
             suf=I
             if [ -f restartphy.nc ]; then
                 if [ $justcheck = 0 ]; then
                     cp restart.nc $resubench/$BENCH/restart$suf.nc
                 fi
                 cmp -s restart.nc $latest/$BENCH/restart$suf.nc
                 if [ $? = 0 ]; then convergeI=I; else convergeI=i; fi
             else
                 # compiled but failed the isoverif test
                 convergeI=x
             fi
      else
          # compilation failed; cleaning up for next compilation
          convergeI=-
          \rm -f libf/grid/dimensions.h
          \rm -f .lock
      fi
   fi

   #########################################################################
      echo Verification de initialisation
   #########################################################################

   if [ $check_ini = 1 ]; then
      cd $LMDZdir
      rm -rf INIT
      mkdir INIT
      cp $BENCH/*def INIT
      cd INIT
      pwd
      $get/Distrib/initialisation.sh
      sed -e 's/grid_resolution=48x36x39/grid_resolution='$resolution'/' initialisation.sh > ini.sh
      chmod +x ini.sh; ./ini.sh
      if [ -f limit.nc ]; then
         var=Tsoil01srf01
         if [ $justcheck = 0 ]; then
             mkdir -p $resubench/START$resolution
             ncks -M -m -h -v $var startphy.nc -O  $resubench/START$resolution/$var.nc
             cp startphy.nc $resubench/START$resolution/
         fi
          cmp -s  startphy.nc  $latest/START$resolution/startphy.nc
         if [ $? = 0 ]; then
             init=OK
         else
             init=noc
         fi
      else
         init=-
      fi
   fi

   ########################################################################
      echo end of test cases
   ########################################################################   
   bench=OK
else
   echo PROBLEME : LE BENCH N EST PAS ALLE AU BOUT
   bench=-
fi

if [ $justcheck = 0 ]; then
    latest=$RESU_D/latest
    \rm -f $latest
    ln -sf  $resubench $latest
fi


cd $LMDZdir/..
LMDZ=`\ls -d LMD*` #Nom du modele LMDZ sur modeles/ : LMDZ4, LMDZ5, LMDZ

svn upgrade # Il faut mettre à jour le svn si la version sur 
            # laquelle le checkout a ete fait est plus ancienne
            # ce qu'on souhaite par ailleurs pour pouvoir ensuite
            # commettre depuis une version ancienne de svn (comme celles
            # des SL du réseau local
svnrel=`svn info $LMDZ | grep 'Changed Rev' | head -1 | awk ' { print $4 } '`
#FH 20160822
if [ "$svnrel" = "" ]; then
  svnrel=`svn info $LMDZ | grep vision | head -1 | awk ' { print $2 } '`
fi

ccc=$converge$convergeNP$convergeD$converge1D$convergeI
if [ "$ccc" = "SNDUI" ]; then ccc="OK ";  fi



########################################################################
# Ectiture du message de bilan
########################################################################

cd $local_d

echo $version'		'$svnrel'	'$bench'	'$ccc '	'$unpun'	'$init'   (ref:' $comparea ')' > tmp.resu
cat > tmp.message <<eod
disponible sur
https://www.lmd.jussieu.fr/~lmdz/Distrib/modipsl.$version.tar.gz

      Test local LMD network, gfortran, 48x36x19
      ==========================================

install version         SVN     Bench   Conv.   1+1=2   Init
                                run     Nnum.      &
                                        /prev.  mpiXomp

eod
cat tmp.resu >> tmp.message
cat >> tmp.message <<eod


                                        ||
                                        \/

S/s/-: 3D standard physics  Converging/runing/not runing
N/n/-: -  new        -                  -
D/d/-: new with debug                   -
U/u/-: unicolonne                       -
I/i/x/-: isotope            Converging/runing/run failed /compiled failed
noc: runs but no convergence
OK <=> SNDUI
eod

cat tmp.message

if [ $mail_address != "" ] &&  [ $justcheck = 0 ]; then
   ssh lmdz@django "mail -s 'Nouvelle version pour install_lmdz.sh' $mail_address < "$local_d"/tmp.message"
#   ssh lmdz@lmdz-forge "mail -s 'Nouvelle version pour install_lmdz.sh' $mail_address < "$local_d"/tmp.message"
fi

#
# clean up of /tmp/lmdz if everything went smoothly
#
grep -q 'OK	OK 	OK2	OK' tmp.resu
RET=$?
if [ ${RET} -eq 0 ]; then
  echo "Quality control checks out for version $version"
  echo "We cleanup $tmpdir/LMDZ$version"
  echo "\rm -rf $tmpdir/LMDZ$version"
  \rm -rf $tmpdir/LMDZ$version
fi

