#!/bin/bash
#
#SBATCH --job-name=NOM_SIMU         # nom du job
#SBATCH -A groupe@cpu
#SBATCH --ntasks=8		   # Nombre de processus MPI ; reecrit par $mpi calcule par setup.sh
#SBATCH --cpus-per-task=8          # Nombre de threads OpenMP ; reecrit par $omp defini dans setup.sh
# de Slurm "multithread" fait bien reference a l'hyperthreading.
#SBATCH --hint=nomultithread       # 1 thread par coeur physique (pas d'hyperthreading)
#SBATCH --time=00:30:00            # Temps d execution maximum demande (HH:MM:SS)
#SBATCH --output=outNOM_SIMU%j     # Nom du fichier de sortie
#SBATCH --error=outNOM_SIMU%j      # Nom du fichier d'erreur (ici commun avec la sortie)
#
# To submit to test queue ; "time" (above) must be max 30 min
# #SBATCH --qos=qos_cpu-dev

set -ex

# Number of MPI processes :
ntasks=8

# For Jean-Zay (replacing the next 3 lines, commented out) 
export OMP_NUM_THREADS=$SLURM_CPUS_PER_TASK
## number of OpenMP threads  
##nthreads=8 
##export OMP_NUM_THREADS=$nthreads 

# private memory for each thread
export OMP_STACKSIZE=800M
# Binding
export OMP_PLACES=cores

simul=NOM_SIMU
ulimit -s unlimited

reseau_local=0
#veget=y
veget=CMIP6
if [ $veget = NONE ] ; then VEGET=n ; else VEGET=y ; fi 

isotopes=n
# If isotopes=y, initialisation_iso will be changed to 0 in iso.def after the 1st run period, to read isotopes in restart files

# Choice of aerosols : n / clim / spla
aerosols=clim
stopsim=201101
ok_guide=y   # y/n guidage ou non
climato=1
orchidee_rev=5004

echo '##############################################################'
echo '# Gestion des repertoires de lancement                                 '
echo '##############################################################'

# Repertoires de la simulation
SCRATCHD=$SCRATCH
STORED=$STORE
MAINDIR=LMDZOR96x95x79
SIMU_dir=$MAINDIR/$simul
SIMUDIR=$STORED/$SIMU_dir

# Repertoires de travail
WWORKD=$SCRATCHD/$SIMU_dir$$
mkdir -p $WWORKD
cd $WWORKD
SCRIPTDIR=$SCRATCHD/$MAINDIR

cp $STORED/$MAINDIR/lmdz_env.sh . ; . lmdz_env.sh
ERADIR=$STORED/$MAINDIR/GUIDE
if [ "$aerosols" = "spla" ] ; then ERA10mDIR=$STORED/$MAINDIR/ERA10m ; fi
LIMITDIR=$STORED/$MAINDIR/LIMIT
SPLADIR=$STORED/$MAINDIR/INPUT_SPLA
DEFDIR=$SIMUDIR/DEF

GET='ln -s'
PUT='mv '


echo '##################################################################'
echo 'Gestion des mois et annees'
echo '##################################################################'

$GET $SIMUDIR/etat
year=`tail -1 etat | awk ' { print $1 } ' | cut -c1-4`
month=`tail -1 etat | awk ' { print $1 } ' | cut -c5-`
echo year $year month $month

if [ "$month" = "" ] ; then
   paran=1
   ym=$year
   next=`expr $ym + 1`
else
   paran=0
   if [ $month = 12 ] ; then
      nextmonth=1
      nextyear=`expr $year + 1`
   else
      nextmonth=`expr $month + 1`
      nextyear=$year
   fi
   if [ `echo $nextmonth | wc -m` = 2  ] ; then
      nextmonth=0$nextmonth
   fi
   ym=$year$month
   next=$nextyear$nextmonth
fi


echo ym $ym
echo mois ancien  : $ym
echo mois nouveau : $next

INI=${SPLADIR}/INITIAL
PERIOD=${SPLADIR}/PERIOD00${month}/SUB

echo '#################################################################'
echo 'Modification de run.def et gcm.def pour prendre en compte la duree du'
echo 'du mois en question.'
echo 'le dayref est modifie pour tricher avec le calendrier (ecrit pour'
echo 'une annee de 260 jours dans le modele).'
echo 'On passe donc comme jour de reference le numero du jour du mois dans'
echo 'une annee en 360 jours.'
echo '#################################################################'

# Choix du calendrier
#AS: La condition if "$climato" = "0" suffit, car "$ok_guide" = "y" est interdit avec $climato" = "1" dans setup.sh (exit ligne 160)
##calend=earth_360d
##if [ "$ok_guide" = "y" -o "$climato" = "0" ] ; then calend=gregorian ; fi
if [ "$climato" = "0" ] ; then calend=gregorian ; else calend=earth_360d ; fi
bisextile=0
if [ $(( $year % 4 )) = 0 -a $calend = gregorian ] ; then bisextile=1 ; fi
if [ $paran = 0 ] ; then
   if [ "$calend" = "gregorian" ] ; then
      ndays=( 31 28 31 30 31 30 31 31 30 31 30 31 )
      if [ $bisextile = 1 ] ; then ndays[1]=29 ; fi
   else
      ndays=( 30 30 30 30 30 30 30 30 30 30 30 30 )
   fi
   #Constants with a leading 0 are interpreted as octal numbers.
   # You can remove the leading zero by parameter expansion: hour=${hour#0}

   nday=${ndays[(( ${month#0} - 1 ))]}
   ndayh=$nday
   dayref=1 ; mm=1 ; while [ $mm -lt ${month#0} ] ; do
    (( dayref = $dayref + ${ndays[(( $mm - 1 ))]} )) ; (( mm = $mm + 1 )) ; done
else
   dayref=1
   if [ "$calend" = "gregorian" ] ; then
      if [ $bisextile = 0 ] ; then nday=365 ; else nday=366 ; fi
   else
      nday=360 ; ndayh=30
   fi
fi

echo CALENDRIER $calend : longueur du mois vrai $year $month $nday dayref=$dayref


echo '####################################################################'
echo '# On va chercher les fichiers necessaires a la simulation'
echo '####################################################################'
#Reminder : we are in $WWORKD = $SCRATCHD/$SIMU_dir = $SCRATCHD/$MAINDIR/$simul

echo DEFDIR $DEFDIR
echo SIMUDIR $SIMUDIR
echo simul $simul

if [ $reseau_local = 0 ] ; then mkdir DEF ; cd DEF ; $GET $DEFDIR/* . ; cd .. ; fi

cp -f DEF/* .
#---The following changes in .def files will only be visible in the running directory (on SCRATCH if $reseau_local = 0)
# They concern variables that change during runtime : nday, dayref, anneeref, ndayh
# The other "sed" were totally or partially moved in setup.sh, to be done in $MAINDIR/DEF/*.def, before creating $MAINDIR/$SIMU (more transparent) 
#sed -e 's/ok_guide=.*.$/ok_guide='$ok_guide'/' DEF/guide.def >| guide.def
#sed -e 's/nday=.*.$/nday='$nday'/' -e 's/dayref=.*.$/dayref='${dayref}'/' -e 's/calend=.*.$/calend='$calend'/' -e 's/anneeref=.*.$/anneeref='$year'/' DEF/run.def >| run.def

#=====!!!!!!!!====!!!!!!====!!!!+++====!!!!!!====!!!!!!!=====!!!!!!====z!!!====!!!!========!!!!!========!!!
##POUR que des TESTS soyent tres RAPIDES (pour ex, verifier fichiers input), ON FORCE nday=1 jour  !!!
#nday=1
#=====!!!!!!!!====!!!!!!====!!!!+++====!!!!!!====!!!!!!!=====!!!!!!====z!!!====!!!!========!!!!!========!!!

sed -e 's/nday=.*.$/nday='$nday'/' -e 's/dayref=.*.$/dayref='${dayref}'/' -e 's/anneeref=.*.$/anneeref='$year'/' DEF/run.def >| run.def
sed -e 's/phys_out_filetimesteps=[[:space:]]*[0-9][0-9]day/phys_out_filetimesteps=  '$ndayh'day/'  DEF/config.def >| config.def
#--- End of *.def changes in the $WWORKD only

${GET} $SIMUDIR/start.$ym.nc start.nc
${GET} $SIMUDIR/startphy.$ym.nc startphy.nc
if [ $climato = 1 ] ; then
   ${GET} $LIMITDIR/limit.nc limit.nc
else
   ${GET} $LIMITDIR/limit.$year.nc limit.nc
fi


echo '####################################################################'
echo '# Imports des fichiers aerosols si flag_aerosol>0 dans config.def, '
echo '# et si dans setup.sh on a "aerosols=clim" ou "aerosols=spla". '
echo '# NOTE: Si "aerosols=n" dans setup.sh, script_SIMU met flag_aerosol=0 et on tourne SANS aerosols' 
echo '####################################################################'
if [ "`grep 'flag_aerosol=' config.def | head -1 | cut -d= -f2`" != 0 ] ; then
  if [ $aerosols = clim ] ; then
    # if [ $climato = 1 ] ; then suf=clim ; else suf=$year ; fi
    suf=clim
    # Le script pourrait être sophistique pour prendre des aerosols interannuels
    ${GET} $LIMITDIR/aerosols.$suf.nc aerosols$year.nc
    if [ ! -f aerosols1980.nc ] ; then ${GET} $LIMITDIR/aerosols.$suf.nc aerosols1980.nc ; fi
    ${GET} $LIMITDIR/aerosols.nat.nc aerosols.nat.nc
  fi

  ## Ca doit etre la meme liste de fichiers rapatriee par setup.sh dans $LMDZ_Init/SPLA_Init 
  ## et interpolee (setup.sh aussi) dans $SPLADIR
  if [ $aerosols = spla ] ; then 
    inputf="wth.dat cly.dat donnees_lisa.nc SOILSPEC.data \
                carbon_emissions.nc sulphur_emissions_antro.nc  \
                sulphur_emissions_nat.nc  sulphur_emissions_volc.nc"
    for file in $inputf ; do ${GET} $INI/$file . ; done

    change="dust.nc "
    for file in $change ; do ${GET} $PERIOD/$file . ; done

    # Le calcul d'emissions de sels marins utilise les vents ERA-10m interpoles sur grille_s (lonv,latu) avec le script era2gcm_uv10m.sh
    # NB : GET=ln -s ; ERA10mDIR contient lui-meme le lien ERA10m vers le repertoire des vents interpoles $REA_uv10m (REA=ERA5, ERAI ou OPERA) 
    ventl="u10m.nc v10m.nc"
    for file in $ventl ; do ${GET} $ERA10mDIR/${year}/${month}/$file . ; done
  fi
fi

#----------------------------------------
# Noveaux forcages a activer a l'avenir 
#   (commentes en attendant) :
#----------------------------------------
#for file in climoz_LMDZ.nc solarforcing.nc  taulwstrat.2D.nc  tauswstrat.2D.nc ; do
#   ${GET} $LIMITDIR/$file $file
#done
#----------------------------------------

${GET} $SIMUDIR/gcm.e gcm.e ; chmod  +x gcm.e


if [ $VEGET = y ] ; then
    set +e ; for t in stomate sechiba ; do cp $SIMUDIR/start_$t.$ym.nc ${t}_rest_in.nc ; done ; set -e
    if [ "`grep RIVER_ROUTING orchidee.def |grep -i y`" ] ; then
      set +e ; ln -s $LMDZ_Init/routing_simple.nc . ; ln -s $LMDZ_Init/routing.nc . 
               cp $SIMUDIR/start_routing.$ym.nc routing_start.nc ; set -e
    fi

#For Orchidee trunk (post-CMIP6), orchidee_pft.def must be copied in addition to orchidee.def 
    \cp -f DEF/orchidee*.def .

# Test sur sechiba_rest_in.nc, 
#  supposant que les restarts pour sechiba, stomate, et routing le cas echeant, 
#  sont soit tous dispo, soit tous absents
    if [ ! -f sechiba_rest_in.nc ] ; then
       echo '#########################################################'
       echo Autoinitialisation d orchidee au besoin
       echo '#########################################################'
       get="ln -s $LMDZ_Init/"
       for file in cartepente2d_15min.nc \
          lai2D.nc soils_param.nc soil_bulk_and_ph.nc alb_bg_modisopt_2D_ESA_v2.nc reftemp.nc ; do ${get}$file ; done

       ln -sf alb_bg_modisopt_2D_ESA_v2.nc alb_bg.nc

       echo ATTENTION : ON UTILISE LES FICHIERS DE L ANNEE 2000
       ${get}PFTmap_15PFT.v1_2000.nc PFTmap.nc
       ${get}woodharvest_2000.nc woodharvest.nc

       sed -e 's/^SECHIBA_restart_in.*./SECHIBA_restart_in=NONE/' \
           -e 's/^STOMATE_RESTART_FILEIN.*./STOMATE_RESTART_FILEIN=NONE/' \
           -i orchidee.def

      if [ $veget = 7994 ] ; then
         get="ln -s $LMDZ_Init/"
         for file in ndep_nhx.nc ndep_noy.nc nfert_cropland.nc nfert_pasture.nc nmanure_cropland.nc nmanure_pasture.nc bnf.nc ; do ${get}$file ; done
      fi

    fi

fi


echo '#################################################################'
echo    'Repertoire contenant les fichiers de reanalyses'
echo '#################################################################'

if [ "$ok_guide" = "y" ] ; then
   \rm -f u.nc v.nc T.nc hur.nc
   if [ -f u.nc ] ; then
      echo PROBLEME D EFFACEMENT DES FICHIERS DE REANALYSES
      exit
   fi
   for var in u v T hur ; do $GET $ERADIR/$year/$month/$var.nc $var.nc ; done
   echo Fin du rapatriement des fichiers de guidage
fi

echo '##################################################################'
echo    'liste des fichiers avant le lancement de la simulation'
echo '##################################################################'
ls -lrt
#diff DEF ./

echo '##################################################################'
echo    'Lancement de la simulation'
echo '##################################################################'

time $run ./gcm.e > listing
if [ ! -f restartphy.nc ] ; then
echo PROBLEME PAS DE FICHIER RESTARTPHY
exit
fi

echo '##################################################################'
echo     'sauvegarde des fichiers de sortie'
echo '##################################################################'

# listing
${PUT} listing ${SIMUDIR}/list$ym
# if the listing for Orchidee is also needed, then uncomment the following line :
#if [ $VEGET = y ] ; then ${PUT} out_orchidee_0000.0000 ${SIMUDIR}/out_orchidee$ym ; fi

# restart(s)
${PUT} restart.nc ${SIMUDIR}/start.$next.nc
${PUT} restartphy.nc ${SIMUDIR}/startphy.$next.nc
if [ $VEGET = y ] ; then for t in sechiba stomate ; do
    f=${t}_rest_out.nc ; if [ -f $f ] ; then ${PUT} $f ${SIMUDIR}/start_$t.$next.nc ; fi ; done 
    f=routing_restart.nc ; if [ -f $f ] ; then ${PUT} $f ${SIMUDIR}/start_routing.$next.nc ; fi
fi

# fichiers "histoires"
# Si on tourne avec xios (et type="one_file") au lieu de ioipsl, on n'a pas besoin de rebuild, on doit juste copier les fichiers
liste_out="histmth histday histhf histmthCOSP Xhistins XhistLES sechiba_history sechiba_history_4dim sechiba_out_2 stomate_history stomate_ipcc_history diag_routing dynzon"
xios_used=0

for fileout in $liste_out ; do
  if [ -f  $fileout.nc ] ; then 
     ${PUT} $fileout.nc ${SIMUDIR}/$fileout.$ym.nc
     xios_used=1
  fi
done

if [ $xios_used = 0 ] ; then
  $GET $SIMUDIR/reb.sh
  chmod +x reb.sh
  ./reb.sh $ym $SIMUDIR $liste_out
fi

if [ -f guide_ins.nc ] ; then ${PUT} guide_ins.nc ${SIMUDIR}/guide_ins.$ym.nc ; fi

echo '##################################################################'
echo     'preparation et lancement de la simulation suivante'
echo '##################################################################'

# Gestion du fichier etat de controle de la simulation
echo $ym OK >> etat
echo $next a faire >> etat
# ${PUT} etat $SIMUDIR/etat # Pas necessaire car etat est un lien vers $SIMUDIR/etat

# set initialisation_iso to 0 for next run to read isotopes from restart files
if [ $isotopes = y ] ; then
   sed -i 's/^initialisation_iso=.*.$/initialisation_iso=0/' $SIMUDIR/DEF/iso.def
fi
set +e ; \rm out* sec* sta* list* rest* gcm.e aer* ; set -e

# Arret si on est arrive au bout
if [ $next =  $stopsim ] ; then
   echo 'On arrive au bout, simulation next:'$next', stopsim:'$stopsim
   # Cas particulier ou on veut chainer plusieurs simulations multi annuelles.
   # pour le tuning automatique.
   # Ici on passe de SCM_1-019 a SCM_1-029
   if [ "${simul:0:3}" = "SCM" ] ; then
      pre="SCM_1-"
      num=`echo $simul | sed -e 's/'$pre'//'`
      # (( num = $num + 10 )) change a cause d un probleme avec 008
      num=`echo $num | awk ' { print $1 + 10 } '`
      num=`printf "%03d\n" $num`
      simul_new=$pre$num
      cd $SCRIPTDIR
      if [ $num -le 250 ] ; then
         sed -e 's/^simul=.*.$/simul='$simul_new'/' -e 's/^\# @ job_nam.*.=.*.$/\# @ job_name = '$simul_new'/' tmp_$simul >| tmp_$simul_new
         sbatch tmp_$simul_new
      fi
   fi
   exit
fi


echo '##################################################################'
echo      'lancement de la simulation suivante tmp_'$simul' depuis :'
echo '##################################################################'
pwd


cd $SCRIPTDIR
sbatch tmp_$simul
