#!/bin/bash
#
#SBATCH --job-name=NOM_SIMU         # nom du job
#SBATCH -A groupe@cpu
# Nombre de processus MPI :
#SBATCH --ntasks=8
# number of MPI processes per node :
#SBATCH --ntasks-per-node=5
# nombre de threads OpenMP
#SBATCH --cpus-per-task=5
# 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)
#


set -ex


ntasks=8
nthreads=4
# number of OpenMP threads:
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
#### reste ada  : export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/smplocal/pub/NetCDF/4.1.3/lib:/smplocal/pub/HDF5/1.8.9/seq/lib


reseau_local=0
veget=y
aerosols=y
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
NCEPDIR=$STORED/$MAINDIR/GUIDE
LIMITDIR=$STORED/$MAINDIR/LIMIT
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


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
calend=earth_360d
if [ "$ok_guide" = "y" -o "$climato" = "0" ] ; then calend=gregorian ; 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 '####################################################################'

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/* .
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
sed -e 's/phys_out_filetimesteps=.*.$/phys_out_filetimesteps= '$ndayh'day 1day 1hr 6hr 6hr/' -e 's/VEGET=.*.$/VEGET='$veget'/' DEF/config.def >| config.def

if [ $aerosols = n ] ; then
 sed -i'' -e 's/^ok_cdnc=.*.$/ok_cdnc=n/' -e 's/^ok_ade=.*.$/ok_ade=n/' -e 's/^ok_aie=.*.$/ok_aie=n/' -e 's/^flag_aerosol=.*.$/flag_aerosol=0/' config.def
fi

${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
for file in donnees_lisa.nc  LUTtau.dat  SOILSPEC.data ; do
   ${GET} $LIMITDIR/$file
done

echo '####################################################################'
echo '# Imports des fichiers aerosols. En fonction du config.def ' 
echo '####################################################################'
if [ "`grep 'flag_aerosol=' config.def | head -1 | cut -d= -f2`" != 0 ] ; 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

# Provisoire pour activer les noveaux forcages.
# A automatiser a l'initialisation
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 [ "$orchidee_rev" -le "3013" ] ; then orchidee_def=orchidee.def
    elif [ "$orchidee_rev" -lt "5004" ] ; then orchidee_def=orchidee_6.0.12.def
    else orchidee_def=orchidee_6.1.def
    fi
    \cp -f DEF/$orchidee_def orchidee.def

    if [ ! -f sechiba_rest_in.nc ] ; then
       echo '#########################################################'
       echo Autoinitialisation d orchidee au besoin
       echo '#########################################################'
       login=`whoami` ; groupe=`echo $login | cut -c2-4`
       LMDZ_Init=$LMDZ_Init/
       get="ln -s $LMDZ_Init"
       for file in cartepente2d_15min.nc \
          routing.nc lai2D.nc soils_param.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
       if [ "$orchidee_rev" -lt "5004" ] ; then
          ${get}PFTmap_IPCC_2000.nc PFTmap.nc
       else
	  # ATTENTION : ON UTILISE LES FICHIERS DE L ANNEE 2000
          ${get}PFTmap_15PFT.v1_2000.nc PFTmap.nc
          ${get}woodharvest_2000.nc woodharvest.nc
       fi
       sed -e 's/^SECHIBA_restart_in=.*./SECHIBA_restart_in=NONE/' \
           -e 's/^STOMATE_RESTART_FILEIN=.*./STOMATE_RESTART_FILEIN=NONE/' \
           -i orchidee.def

    fi
fi


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

if [ "$ok_guide" = "y" ] ; then
   \rm -f u.nc v.nc T.nc
   if [ -f u.nc ] ; then
      echo PROBLEME D EFFACEMENT DES FICHIERS DE REANALYSES
      exit
   fi
   NCEP="$GET $NCEPDIR/$year/$month/"
   for var in u v T ; do ${NCEP}$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 $ntasks ./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

# 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 ; fi

# fichiers "histoires"
$GET $SIMUDIR/reb.sh
chmod +x reb.sh
./reb.sh $ym $SIMUDIR histmth histday histhf histmthCOSP sechiba_out_2 stomate_ipcc_history sechiba_history 
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 +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
