#!/bin/bash

# Rerun a series of 1D simulations
# ================================
# Reruning a set of test cases on a series of .def files
# by default the default files are retrieved from a tuning
# exeperiment, but it could be generalized

# 1. main function
# ----------------
# called at the end of the script
# calling all other functions

function main {

 nbests=10
 liste_cas="arm_cu,rico,amma,FIRE/REF,sanduslow,sanduref,sandufast,EUROCS/REF,KB2006/MESONH,LBA/REF"
 local_d=$( pwd )

 # installing LMDZ, the LMDZ SCM and running test cases
 install_scm_cases

 htexplo_wd=ricard:/data/musat/d_Tuning/HT_220925/explorer/WORK/PhyPar-CPTW-1D3D-Ex3-tol0.03
 htexplo_wd=ricard:/data/crio/ITUNE/htexplo/WORK/HTRIG
 #get_best_def_files_from_htexplo ; exit
 list_sims="6A L95PartIIBest1 $( get_best_def_files_from_htexplo )"
echo $list_sims

 # Running selected simulations
 run_bests $list_sims

 run_diags $list_sims

}

# 2. installing LMDZ/1D and a series of test cases
# ------------------------------------------------
# This step is based on the eduplanet distribution of LMDZ

function install_scm_cases {
 cd $local_d
 if [ ! -d eduplanet ] ; then
    git clone ricard:WWW/git_d/eduplanet.git 
    cd eduplanet
    ln -s ~/LMDZ/pub/netcdf/netcdf4_hdf5_seq .
    cd -
 fi
 scm_d=$PWD/eduplanet/LMDZseq/1D
 # Il faut inclure une option de netoyage optionnel
 # if [ -d $scm_d/EXEC ] ; then mv $scm_d/EXEC $scm_d/EXEC$$ ; fi
 cd eduplanet
 if [ ! -d LMDZseq/1D/EXEC ] ; then
     bash planet.sh -g 79 SCM:$liste_cas > out1D0 2>&1
 fi
 cd $local_d
}


# 3. getting best physiq.def files from an htexplo experiment
# -----------------------------------------------------------
# Here the experiment is assumed to be accessibles through
# rsync and to have been run in the htexplo framework for
# the organisation of directory
# The nbest simulations are retrieved from the \texttt{max.csv}
# file.

function get_best_def_files_from_htexplo {
 cd $scm_d
 \rm -f max.csv ; rsync -av $htexplo_wd/max.csv . > rsync.log 2>&1
 if [ -f max.csv ] ; then
    set -u ; local bests_=$( tail +2 max.csv  | cut -d, -f1 | head -$nbests ) ; set +u
 else
    rsync -av $htexplo_wd/'score*.csv' . >> rsync.log 2>&1
    local bests_=$( cat score*[0-9].csv | sort -n -t, -k$(head -1 - | awk -F',' '{print NF}') | grep SCM | head -$nbest | cut -d, -f1 )
 fi
 for s in $bests_ ; do
    # getting the wave number from the simulation name SCM-Wave#-sim#
    wave=$( echo $s | cut -d- -f2 )
    rsync -av $htexplo_wd/WAVE$wave/DEF/physiq.def_$s $scm_d/INPUT/PHYS/ >> rsync.log 2>&1
 done
 echo $bests_
}

# 3. getting best physiq.def files from an htexplo experiment
# -----------------------------------------------------------
# runing the best simulations using \lstinline{1D/run.sh}

function run_bests {
  cd $scm_d
  local sims_="$*"
  local cas_="$( echo $liste_cas | sed -e 's/,/ /g' )"
  sed -i'' -e 's/fcm=1/fcm=0/' -e 's/^LLM=.*$/LLM=95/' run.sh
  sed -e "s/listedef=.*$/listedef=\"$( echo $sims_ )\"/" \
      -e "s:liste_cas=.*$:liste_cas=\"$( echo $cas_ )\":" \
         run.sh > runbests.sh
  # Option pour ne pas rerunner les simulations existantes
  # Il faudrait en faire une option de run.sh
  sed -i'' -e 's:^.*mkdir -p $EXECDIR:if [ ! -f $EXECDIR/hourly.nc ] ; then mkdir -p $EXECDIR:' \
           -e 's/done  #cas/fi ; done/' \
           -e 's/ok_debug=true/ok_debug=false/' \
           -e 's/done # model config/done ; exit/' \
           runbests.sh

  bash runbests.sh > out1D 2>&1
}

# 4. Running diagnostics
# -----------------------------------------------------------

function run_diags {
  cd $scm_d
  defs="6AL79 $( for d__ in $* ; do echo ${d__}L95 ; done )"
  for cas_ in $( echo $liste_cas | sed -e 's/,/ /g' ) ; do
      echo cas_ $cas_
      local cas_out_d=$PWD/diags_d/$cas_
      mkdir -p $cas_out_d
      for def in $defs ; do
         echo "use EXEC/${def}/$cas_/histhf.nc ; go white" > tmp.jnl
         case $cas_ in
            arm_cu|rico|sanduslow|sanduref|sandufast|FIRE/REF) 
            cat>>tmp.jnl<<eod
            reg/z=70000:101300
            fill/lev=(0.2)(1,4,1)(6,10,2)(15,25,5)(50)(70)(Inf)/title="$cas_ $def RNEB" 100*rneb
eod
            ;;
            amma|EUROCS/REF|KB2006/MESONH|LBA/REF) 
            cat>>tmp.jnl<<eod
            fill/lev=(-Inf)(-10,10,2)(Inf)/pal=blue_darkred/title="$cas_ $def Q1" 86400*(dtcon+dtthe)
            contour/o/col=14/lev=(10,90,10) 100*rneb
            contour/o/col=7/lev=(1,7,2) 100*rneb
eod
            ;;
            *) echo cas non prevu ; exit 1
         esac
         echo frame/file=tmp.gif >> tmp.jnl
         rm -f tmp.gif
         ferret -script tmp.jnl
         convert tmp.gif $PWD/diags_d/$cas_/$def.png
      done
      cd $cas_out_d
      nup=$( unset LANG ; ls *.png | wc -w | awk ' { print int(($1-1)^0.5)+1 }' )
      pdfjam --nup ${nup}x${nup} *.png --outfile $local_d/$( echo $cas_ | sed -e 's:/::' ).pdf --landscape
      cd -
  done
}


# Finally running the main function
# ---------------------------------
main
