#!/bin/bash
########################################################
# This file loads the required modules and sets the paths for simulations
# To modify the paths:
#    1) In the <set_env> function, find the section corresponding to your machine
#    2) Modify the variables, which are documented in the *) section of <set_env>
# See the end of <set_env> for the explanation of each
########################################################

# <root_dir> will be set by sed by setup.sh here
pwd

root_dir=.
check_loc=1

echo root_dir $root_dir
if [[ ! -d $root_dir ]]; then
  echo "STOP in $PWD/lmdz_env.sh: root_dir $root_dir not found, either you are running on an unsupported cluster, or the initialisation failed midway"; exit 1
fi
pwd
echo root_dir $root_dir
if [[ ! -f $root_dir/lmdz_env.sh ]]; then
  echo "STOP in $PWD/lmdz_env.sh: lmdz_env.sh not found on root_dir $root_dir, either you are running on an unsupported cluster, or the initialisation failed midway"; exit 1
fi
if [[ ! -f $root_dir/.lmdz_setup_root_dir  && $check_loc = 1 ]]; then
  echo "STOP in $PWD/lmdz_env.sh: file .lmdz_setup_root_dir not found in root_dir $root_dir"; exit 1
fi

pub_store=1
PARALLEL=1

function get_hostname {
  if grep -q "Adastra" /etc/motd 2>/dev/null ; then
    hostname="adastra"
  elif which idrquota &> /dev/null; then
    hostname="jean-zay"
  else
    hostname=$(hostname)
  fi
}

function set_env {  # Platform-specific
  case ${hostname:0:5} in
#-------------------------------------------------------------------------
    jean-) # Jean-zay, Idris-CNRS super computer
#-------------------------------------------------------------------------
      module purge
      compilo=19.0.4 # available 2013.0, 2017.2
      module load intel-compilers/$compilo
      #module load intel-mpi/$compilo
      module load intel-mkl/$compilo
      module load hdf5/1.10.5-mpi
      module load netcdf/4.7.2-mpi
      module load netcdf-fortran/4.5.2-mpi
      module load subversion/1.9.7
      #Pour module gcc, voir : https://trac.lmd.jussieu.fr/LMDZ/wiki/PortageJeanZay
      #module load gcc/6.5.0
      module load nco
      module load cdo
      # Imputation de la consommation sur le groupe (projet) actif par defaut,
      #   idrproj indique le groupe (projet) actif par defaut
      #   idrproj -d newproj   redefinit "newproj" en tant que  projet actif,
      #        alors $STORE, $WORK etc vont designer les espaces de "newproj")
      account="lmd"  # $(idrproj | grep active | awk '{ print $1}') doesn't work on compute nodes
      ARCH="X64_JEANZAY_PBIOIPSL"
      SIMRUNBASEDIR="$SCRATCH/$(basename $root_dir)"
      LMDZD="$WORK/LMDZD"
      LMDZ_INIT="$WORK/LMDZ/pub"
      NB_MPI_MAX=2000
      NB_OMP_MAX=20
      NB_CORE_PER_NODE_MAX=0
      MPICMD="srun -n"
      RUNBASHCMD="srun -A $account@cpu --label -n 1 -c"
      #SUBMITCMD="sbatch -A $account@cpu"
      submitcmd() {
         sbatch -A $account@cpu $1
      }
      ;;
#-------------------------------------------------------------------------
    spiri) # Spirit : IPSL cluster
#-------------------------------------------------------------------------
      module purge
      module load subversion/1.13.0
      module load gcc/11.2.0
      module load openmpi/4.0.7
      module load cdo/2.3.0

      ARCH="X64_MESOIPSL-GNU"
      SIMRUNBASEDIR="$SCRATCH/$(basename $root_dir)"
      LMDZD="$root_dir/LMDZD"
      LMDZ_INIT="$HOME/LMDZ/pub"
      NB_MPI_MAX=5
      NB_OMP_MAX=1
      NB_CORE_PER_NODE_MAX=0
      N_HYPERTHREADING=1
      MPICMD="mpirun -np"  # on spirit, we can't run MPI using srun from within sbatch
      RUNBASHCMD="bash"
      #SUBMITCMD="sbatch"
      submitcmd() {
         sbatch $1
      }
      ;;
#-------------------------------------------------------------------------
    adast) # Adastra, Cines computing center
#-------------------------------------------------------------------------
      module purge
      module load PrgEnv-gnu  # we need to load the env because lmdz links some shared libraries
      module load gcc/13.2.0  # required, see https://dci.dci-gitlab.cines.fr/webextranet/user_support/index.html#prgenv-and-compilers
      export CRAY_CPU_TARGET=x86-64  # to suppress warnings during Cmake netcdf95 build
      export FI_CXI_RX_MATCH_MODE=hybrid  # 09/24 otherwise we get random SIGABRT e.g. "libfabric:2490616:1725895288::cxi:core:cxip_ux_onload_cb():2657<warn> c1456: RXC (0x5130:21) PtlTE 84:[Fatal] LE resources not recovered during flow control. FI_CXI_RX_MATCH_MODE=[hybrid|software] is required"

      function cdo {  # cdo is available as a spack cmd which requires a specific, incompatible env
        unset cdo
        module purge
        # Commentaire conserve pour l'option "develop". Ca a marché puis plus
        #module load develop GCC-CPU-4.0.0 cdo/2.4.2-omp-mpi
        module load GCC-CPU-3.2.0 cdo/2.4.2-omp-mpi
        cdo "$@"
        set_env
      }

      function ferret {
        unset ferret
        module purge
        module load GCC-CPU-3.1.0
        module load ferret
        ferret "$@"
        set_env
      }

      account=$(/usr/sbin/my_project.py -l 2>&1 | head -1 | cut -d " " -f 3- | cut -c 5-)
      ARCH="X64_ADASTRA-GNU"
      SIMRUNBASEDIR="$SCRATCHDIR/$(basename $root_dir)"
      LMDZD="$WORKDIR/LMDZD"
      LMDZ_INIT="$WORKDIR/LMDZ/pub"
      NB_MPI_MAX=2000
      NB_OMP_MAX=200
      NB_CORE_PER_NODE_MAX=192
      N_HYPERTHREADING=1  # Adastra has SMT=2 enabled, but we found no actual performance improvement for the latlon model. Maybe useful for Dynamico ?
      MPICMD="srun -n"
#      RUNBASHCMD="srun --label --account=$account --constraint=GENOA --ntasks-per-node=1 -n 1 --time=00:15:00 -c"
      RUNBASHCMD="bash"  # On Adastra the docs says we can use login nodes for compilation
      #SUBMITCMD="env $(env | grep -E "SLURM_|SBATCH_|SRUN_" | cut -d= -f1 | awk '{print "-u " $0}' | tr '\n' ' ' ) sbatch --constraint=GENOA --account=$account"  # we need to remove the existing SLURM variables otherwise they may be unexpectedly inherited by the submitted script
      submitcmd() {
        env $(env | grep -E "SLURM_|SBATCH_|SRUN_" | cut -d= -f1 | awk '{print "-u " $0}' | tr '\n' ' ' ) sbatch --constraint=GENOA --account=$account $1
      }  # we need to remove the existing SLURM variables otherwise they may be unexpectedly inherited by the submitted script
      ;;
#-------------------------------------------------------------------------
    *)  # Local machine.
#-------------------------------------------------------------------------
      SIMRUNBASEDIR="$root_dir/SCRATCH/"  # Where the simulations will be executed ($SIMRUNBASEDIR/LMDZ_Setup/...)
      LMDZD="$root_dir/../LMDZD"  # Where the sources will be downloaded and compiled
      if [[ $pub_store ]] ; then LMDZ_INIT="$HOME/LMDZ/pub" ; else LMDZ_INIT="$root_dir/LMDZ/pub" ; fi
      # Old fortran versions
      if [ $( gfortran --version | head -1  | awk ' { print $NF } ' | cut -d. -f1 ) -le 9 ] ; then 
          gfortranv=gfortran9 ; archdir="-arch_dir arch"
          if [ ! -d $LMDZD/arch ] ; then mkdir -p $LMDZD ; cd $LMDZD ; 
            wget http://lmdz.lmd.jussieu.fr/pub/src_archives/misc/arch/LMDZ/arch-local-gfortran9.tar
            tar xvf arch-local-gfortran9.tar
            cd -
          fi
      else
          gfortranv=gfortran ; archdir=
      fi
      if [[ $PARALLEL = 0 ]] ; then
         ARCH="local-${gfortranv} $archdir"  # The arch file to use
         NB_MPI_MAX=1  # Max number of MPI cores (only for running simulations)
         NB_OMP_MAX=1  # Max number of OMP threads (only for running simulations)
         MPICMD="" # command to run an mpi executable, as $MPICMD <nprocs> <script>
      else
         ARCH="local-${gfortranv}-parallel $archdir"  # The arch file to use
         NB_MPI_MAX=2  # Max number of MPI cores (only for running simulations)
         NB_OMP_MAX=2  # Max number of OMP threads (only for running simulations)
         MPICMD="mpirun -np" # command to run an mpi executable, as $MPICMD <nprocs> <script>
      fi

      NB_CORE_PER_NODE_MAX=0  # Max number of cores per node (real cores, not hyperthreading - only for running simulations, cluster-specific)
      N_HYPERTHREADING=1  # How many hyperthreading threads per physical core
      RUNBASHCMD="bash" # command to run a bash job, as $runbashcmd (nthreads) <script> [nthreads only supplied if =/="bash"]
      #SUBMITCMD="."  # command to sumbit a job, as $submitcmd <script>
      submitcmd() {
         nohup bash $1 > out.$$ 2>err.$$ &
      }
      ;;
  esac
}

#-----------------------------------------------------------------------------------------------------
function wget_pub() { # geting file from http:lmdz... and saving on $LMDZ_INIT
#-----------------------------------------------------------------------------------------------------
  local dir=$1
  local file=$2
  local target_dir=$LMDZ_INIT/$dir
  if [ ! -f $target_dir/$file ] ; then
     mkdir -p $target_dir
     cd $target_dir
     wget --no-check-certificate -nv "http://lmdz.lmd.jussieu.fr/pub/$dir/$file"
     cd -
  fi
}

#-----------------------------------------------------------------------------------------------------
function cp_from_pub() { # geting file from http:lmdz... and saving on $LMDZ_INIT
#-----------------------------------------------------------------------------------------------------
  local dir=$1
  local file=$2
  cp -f $LMDZ_INIT/$dir/$file .
}

#-----------------------------------------------------------------------------------------------------
function ln_from_pub() { # geting file from http:lmdz... and saving on $LMDZ_INIT
#-----------------------------------------------------------------------------------------------------
  local dir=$1
  local file=$2
  ln -sf $LMDZ_INIT/$dir/$file .
}

#-----------------------------------------------------------------------------------------------------
function get_input_files() {
#-----------------------------------------------------------------------------------------------------
  local method=$1
  local target=$2
  case $target in

      Orchidee) local files="PFTmap_IPCC_2000.nc cartepente2d_15min.nc routing.nc routing_simple.nc lai2D.nc \
      alb_bg_modisopt_2D_ESA_v2.nc reftemp.nc \
      soils_param.nc woodharvest_2000.nc PFTmap_15PFT.v1_2000.nc soil_bulk_and_ph.nc  \
      ndep_nhx.nc ndep_noy.nc nfert_cropland.nc nfert_pasture.nc nmanure_cropland.nc nmanure_pasture.nc bnf.nc" ;;

      AerChem) local files="aerosols1850_from_inca.nc aerosols9999_from_inca.nc" ;;

      SPLA_WA/emissions) local files="donnees_lisa.nc SOILSPEC.data              \
         cly.dat $( for i in $(seq -w 1 12 ) ; do echo dust$i.nc ; done ) wth.dat   \
         carbon_emissions.nc sulphur_emissions_antro.nc sulphur_emissions_nat.nc \
         sulphur_emissions_volc.nc" ;;

      *) echo target $target non available in get_input_files ; exit 1 ;;
  esac

  if [[ $method != wget_pub && $method != ln_from_pub ]] ; then
     echo method $method not available in get_input_files ; exit 1
  fi
  for file in $files ; do $method 3DInputData/$target $file ; done

}

get_hostname
echo "Setting up lmdz_env on $hostname"
set_env

# A reactiver eventuellement pour permettre que les variables soient exportées dans les sous-shell
# Mais certaines ne sont pas déclarées suivant les configs comme N_HYPERTHREADING
#
# export ARCH=$ARCH
# export SIMRUNBASEDIR=$SIMRUNBASEDIR
# export LMDZD=$LMDZD
# export LMDZ_INIT=$LMDZ_INIT
# export NB_MPI_MAX=$NB_MPI_MAX
# export NB_OMP_MAX=$NB_OMP_MAX
# export NB_CORE_PER_NODE_MAX=$NB_CORE_PER_NODE_MAX
# export N_HYPERTHREADING=$N_HYPERTHREADING
# export MPICMD=$MPICMD
# export RUNBASHCMD=$RUNBASHCMD
