#!/bin/bash

set -e
unset LANG

# Installation de LMDZ et PHYEX
# =============================
#
# Auteurice : Najda Villefranque. Fréjus, mai 2023
# -----------
#
# Script écrit par Najda Villefranque à l'atelier Fréjus 2023
#    pour péréniser l'installation du couplage LMDZ/PHYEX mis
#    au point par Sébastien Riette, Quentin Rodier, Yann Seti,
#    Najda Villefranque, Jean-Baptiste Madeleine et Frédéric
#    Hourdin
#
# Principe:
# ---------
#
#    LMDZ est récupéré via la logistique install_lmdz.sh 
#      (les sources sont gérés sous subversion mais on récupère un tar)
#    git clone d'une version de PHYEX contenant des sources spécifiques
#    pour LMDZ.
#
# Mises à jour principales:
# -------------------------
#
# - *27 mai 2023 (FH)*:
#    On repart du install_lmdz.sh standard
#    On fait une installation ultra rapide sans compiler
#    On teste si on a déjà installé Netcdf
#
# - *5 juin 2024 (FH)*: 
#    Recupération des versions développées à Lege en 2024
#    Et lancement d'un test 3D
#
# - *7 octobre 2024 (AI)*: 
#    Depart d'une version recenete de Phyex validee pour LMDZ
#    version git : de1ca4b (commit du 6 sep, 2024)
#    depart de la version post Lege (FH)
#    Couplage avec le rayonnement
#
# FH : Frédéric Hourdin
# AI : Abderrahmane Idelkadi
#================================================================


#                         main function
#                         =============
#
# Cette fonction est exectutée toute à la fin et est une suite
# d'appels aux différentes fonctions

function main {
default_settings
installing_lmdz
installing_lmdz_1d
downloading_phyex
merging_lmdz_with_phyex
running_phyex
}

#            Defaults , directories, options 
#            ===============================

function default_settings {

# Choix de la version de physiqex_mod.F90
version_physiqex=git      # Version du git phyex. Conseillé hors dev et beta tests
version_physiqex=Lege     # Lege/20240605/git, premiere version 3D
version_physiqex=Frejus   # Frejus/20230528/git, premiere version de ArmCu
version_physiqex=Paris    # Paris/20260421, version couplée avec le transfert radiatif

ESKEFREDHOAREPAREMAKEMAKE=BEN_OUI_BIEN_SUR
ON_A_NETTOYE_LES_NOMS_DE_FICHIERS_DIRECTEMENT_DANS_PHYEX=0

lancer_le_1D_avant_liens_phyex=1
lancer_le_1D=1
lancer_le_3D=0
rad=oldrad #  oldrad/rrtm/ecrad
day_step=1440


# Pour memoire : anciennes versions testées
case $version_physiqex in
    git|Frejus) # Combinaison post Frejus
    commit=9815a0ea679f079e88581b6ee06f0d8ca53ee62b
    version='-v 20230529.trunk -unstable' # Version utilisee côté le CNRM 
    svn_install=4552
    ;;
    Lege) # Combinaison post Lege
    version='-v 20240508.trunk'
    svn_install=4938
    commit=ec18f73bcbda41cce7858c0ca509fbf947453019
    ;;
    Paris) # Combinaison Paris
    #version='-v 20241121.trunk'
    version='-v 20260420.trunk -unstable -r 6182'
    version='-v 20260512.trunk'
    commit=de1ca4b62f0b0b383f9d5f21faed0233fda9018c # OK
    #commit=5a552ef92ae4ee5b5646f6762d6763ecf35679ac # Special LMDZ
    # commit=bd6655bf10572f21811e934f6422cd13f3738a57 # recent
    svn_install=6182
esac

# CAS Leg, Frejus et git on doit pas compiler avec ecrad #
if [ $rad = ecrad ] ; then
   if [ $version_physiqex = Lege -o $version_physiqex = Frejus -o $version_physiqex = git ] ; then 
      echo  Ne compile pas avec ecrad, problem de conflit sur yomhook  
      exit  
   fi
fi

##############################################
#        INIT ENVIRONNEMENT DE TRAVAIL       #
##############################################

lmdz_name=LMDZ`echo $version | sed -e 's/ //g' -e 's/\-v//' -e 's/\-unstable//' -e 's/\-r/r/'`
lmdzdir=`pwd`/$lmdz_name
phylmd=${lmdzdir}/modipsl/modeles/LMDZ/libf/phylmd/
phyex=${lmdzdir}/PHYEX
#svn_rel=6182

wdir=$HOME/work/dephy/frejus/couplage_phydyn/
wdir=/tmp/phyex
wdir=`pwd`

mkdir -p $wdir
cd $wdir
}


                        # Installing LMDZ
                        # ===============

function installing_lmdz {

# Setting LMDZ name and directory
# -------------------------------
if [ -d $lmdzdir ] ; then
      echo Le repertoire $lmdzir est deja present
      echo Le detruire ou sauvegarder avant de relancer
      exit
fi

# Getting install_lmdz.sh with imposed revision
# ---------------------------------------------
lmdz_svn_path=https://svn.lmd.jussieu.fr/LMDZ
install_lmdz=install_lmdz_$svn_install.sh
if [ ! -f $install_lmdz ] ; then
   svn checkout $lmdz_svn_path/BOL/script_install ./ --depth empty
   svn up -r $svn_install install_lmdz.sh
   mv install_lmdz.sh $install_lmdz
fi

# Running install_lmdz.sh
# -----------------------

echo '##################################################################'
echo ' Installation de LMDZ'
echo ' -bench 0 tant qu on ne fait que du 1D'
echo ' -netcdf $wdir/netcdf pour compiler netcdf une fois pour toutes'
echo log dans $wdir/log.$$
if [ -d ~/LMDZ/pub ] ; then nc_d=~/LMDZ/pub ; else nc_d=$wdir/netcdf ; fi
time ( bash $install_lmdz $version -bench 0 -rad $rad -netcdf $nc_d -name $lmdz_name > $wdir/log.$$ 2>&1 )
echo '##################################################################'
svn_rel=`svn info $lmdzdir/modipsl/modeles/LMDZ | grep 'Last Changed Rev:' | awk ' { print $NF } '`
}


                           # Installing 1D
                           # -------------

function installing_lmdz_1d {
cd $lmdzdir
wget https://lmdz.lmd.jussieu.fr/pub/1D/1D.tar.gz
tar xf 1D.tar.gz
cd 1D
sed -i'' -e 's:^listecas=.*$:listecas="arm_cu":' -e 's/^rad=.*$/rad='$rad'/' -e 's/^day_step=.*$/day_step='$day_step'/' run.sh
sed -i'' -e 's/^rad=.*$/rad='$rad'/' bin/compile

cd INPUT/PHYS
sed -e '/aller dans config.def/s/^.*$/iflag_physiq=1/' physiq.def_6A >> physiq.def_PHYLMD
sed -e '/aller dans config.def/s/^.*$/iflag_physiq=2/' physiq.def_6A >> physiq.def_PHYEX

# Lancement eventuel automatique du 1D
if [[ $lancer_le_1D_avant_liens_phyex == 1 ]] ; then
    cd $lmdzdir/1D/
    time ./run.sh > avant_modif.log$$ 2>&1
    mv EXEC EXEC0 ; cp -f run.sh run0.sh
fi
}



#             DOWNLOADING PHYEX
#             =================

function downloading_phyex {

# Utiliser la variable commit pour viser des revisions robustes
# de phyex pour des tests systématiques une fois le couplage finalisé
if [ ! -d $phyex ] ; then 
  cd $lmdzdir
  git clone https://github.com/UMR-CNRM/PHYEX.git
fi
cd $phyex
git checkout master
git pull origin master
git checkout $commit
}

# LINK PHYEX SOURCES IN LMDZ  
function merging_lmdz_with_phyex {
cd $phylmd
cp -r . ../phylmdorig
ln -s $phyex/src/common/*/* .
ln -sf $phyex/src/lmdz/aux/* .
sed -e 's/D%NIJE =.*$/D%NIJE=KLON/' -e '/PHYEX%MISC%TLES%LLES/aPHYEX%MISC%TLES%LLES_CALL=.FALSE.' $phyex/src/lmdz/ext/mode_init_phyex.F90 > mode_init_phyex.F90

# Pour les routines en commun on ne fait pas des liens.
# Pour le moment on utilise le output_physiqex_mod.F90 de la svn LMDZ
# mv output_physiqex_mod.F90 output_physiqex_mod.orig
# cp -f $phyex/src/lmdz/ext/output_physiqex_mod.F90 .

mv physiqex_mod.F90 physiqex_mod.orig

case $version_physiqex in
   git) cp $phyex/src/lmdz/ext/physiqex_mod.F90 . ;;
   Frejus) wget https://lmdz.lmd.jussieu.fr/pub/install_phyex/Frejus/physiqex_mod.$version_physiqex
           cp physiqex_mod.$version_physiqex physiqex_mod.F90 ;;
   Lege) cd ../..
         wget https://lmdz.lmd.jussieu.fr/pub/install_phyex/Lege/phyex_patch_05062024.tar
         tar xvf phyex_patch_05062024.tar 
	 cd - ;;
   Paris) cd ../.. 
	  # wget https://lmdz.lmd.jussieu.fr/pub/install_phyex/Paris/phyex_patch_09042026.tar
	  # tar xvf phyex_patch_09042026.tar
	  # wget https://lmdz.lmd.jussieu.fr/pub/install_phyex/Paris/phyex_patch_20260422.tar
	  # tar xvf phyex_patch_20260422.tar
	  wget https://lmdz.lmd.jussieu.fr/pub/install_phyex/Paris/phyex_patch_20260512.tar
	  tar xvf phyex_patch_20260512.tar
	  cd - ;;
   *) echo cas non prevu ; exit 1
esac

touch physiqex_mod.F90 # Pour forcer la recompilation

# PATCH SI ON NE COMPILE PAS AVEC ECRAD
  if [ $svn_rel -le 4836 ] ; then
     # Avant la version de mars 2024
     ln -s ecrad/yom* ecrad/abor1.F90 ecrad/abor1.intfb.h ecrad/parkind1.F90 .
  else
     ln -s ecrad/ifsaux/yom* ecrad/ifsaux/abor1.F90 ecrad/include/abor1.intfb.h ecrad/ifsaux/parkind1.F90 .
     #ln -s ecrad/drhook/yomhook_dummy.F90 .
  fi
if [ -f $phyex/src/lmdz/ext/yomhook.F90 ] ; then
   if [ "$rad" != "ecrad" ] ; then
      ln -sf $phyex/src/lmdz/ext/yomhook.F90 .
   fi
fi

if [[ $ON_A_NETTOYE_LES_NOMS_DE_FICHIERS_DIRECTEMENT_DANS_PHYEX == 0 ]] ; then
   mv modd_dimphyexn.F90 modd_dimphyex.F90
   for name in `grep -i 'END MODULE' modd*n.F90 | cut -d: -f1 | sed -e 's/n.F90//'` ; do mv ${name}n.F90 ${name}_n.F90 ; done
   mv hypgeo.F90 modi_hypgeo.F90
   mv hypser.*90 modi_hypser.F90
   mv tools.F90 mode_tools.F90
   if [ -f momg.F90 ]       ; then mv momg.F90 modi_momg.F90 ; fi
   if [ -f shuman_phy.F90 ] ; then mv shuman_phy.F90 mode_shuman_phy.F90 ; fi
   if [ -f shuman_mf.F90 ] ; then mv shuman_mf.F90 modi_shuman_mf.F90 ; fi
   # Nettoyé dans les dernières versions
fi
}

#               Running LMDZ_phyex simulations
#               ==============================

function running_phyex {
############################################################
echo RUNING 1D CASES WITH LMDZ AND LMDZ-PHYEX
echo Results in $lmdzdir/1D/log.$$
############################################################

cd $lmdzdir/1D
sed -i'' -e 's/^listedef=.*$/listedef="PHYLMD PHYEX"/' run.sh 
time ./run.sh > log.$$ 2>&1
wget https://web.lmd.jussieu.fr/~hourdin/phyex/compare.sh
bash compare.sh >> log.$$ 2>&1
if [ -f arm_cu.gif ] ; then
    echo Visualise 1D results in $PWD/arm_cu.gif
else
    echo Something went wrong with the 1D test
    echo check in $PWD/log.$$
fi

if [ $lancer_le_3D -le 1 ] ; then
   echo Running 3D bench
   cd ${lmdzdir}/modipsl/modeles/LMDZ/
   if [ ! -d DEF ] ; then
      echo 3D pas prevu
   else
      echo "./makelmdz_fcm -rad $rad -arch local -j 8 -d 32x32x39 -v false gcm" > compile.sh
      chmod +x compile.sh
      bash ./compile.sh > log.$$ 2>&1
      if [ $? = 0 ] ; then
          cp -f bin/gcm.e DEF/gcm.e
      else
          echo 3D compilation failed
          echo look in $PWD/log.$$
          exit
      fi
      if [ $rad == ecrad ] ; then
         cp -f DefLists/namelist_ecrad DEF/.
         ln -s ../libf/phylmd/ecrad/data DEF/.
	 cp -f DEF/physiq.def.ecrad DEF/physiq.def
      fi
      cd DEF/
      echo running 3D test
      echo outputs in `pwd`
      echo log file and phys.nc containing the results of the simulation
      ./gcm.e > out 2>&1
   fi
fi
}

main
