#!/bin/bash

#---------------------------------------------------------------------------
#  Getting and interpolating reanalaysis on the LMDZ grid for nudging
#---------------------------------------------------------------------------
#
#  Developed by LMDZ team :
#    F. Hourdin, A. Sima et al.
#
#  2025/10/03 : factorizing the code. era2gcm_tuto.sh should be obsolete.
#               u10m and v10m to be added optionnally to make 
#               era2gcm_uv10m.sh obsolete too
#               Automatic access to reanalysis on lmdz.lmd.jussieu.fr
# 
#
#  NB: for "cleanest" guiding, the 1st step of the next month should be
#     added at the end of each month.
#     wget http://forge.ipsl.jussieu.fr/igcmg/browser/TOOLS/INTERP_NUDGE
#      documented on LMDZpedia (search for "Guidage" )
#
#---------------------------------------------------------------------------
# Requires : netcdf, ferret, nco, cdo
#---------------------------------------------------------------------------
. lmdz_env.sh
set -eu

#---------------------------------------------------------------------------
# User choices
#---------------------------------------------------------------------------
# Periode :
mth_i=200001
mth_f=202012
#
vars="u v ta q"
vars="u v"
#
# Choix des fichiers de guidage ("rea"nalyses) : ERA5, ERAI, OPERA
rea="ERAI"
resol_rea=075

#---------------------------------------------------------------------------
# Paths
#---------------------------------------------------------------------------
ERA5_PATH="/gpfsstore/rech/psl/rpsl376/ergon/ERA5/"
ERAI_PATH="/gpfsstore/rech/psl/rpsl376/ergon/ERAI/"
ERAI_PATH="/lustre/fswork/projects/rech/wfe/rgzi027/LMDZ/pub/3DInputData/ReAnalyses/ERAI"
#/lustre/fswork/projects/rech/wfe/rgzi027/LMDZ/pub/3DInputData/ReAnalyses/ERAI/NETCDF/GLOBAL_075/4xdaily/AN_PL/2014/

#@ADS ERA5_PATH="/lus/work/CT1/cad15221/abarral/ERA_TMP/"  # /!\ temp for test only !
#@ADS ERAI_PATH=""  # /!\ temp for tests only!
#@ADS echo "/!\ Nudging files are not available on Adastra for now !"; exit 1  # comment this line for tests
#@ADS SCRATCH=$SCRATCHDIR

GRID_DIR=./INIT

#---------------------------------------------------------------------------
#Utilite du block suivant a re-examiner :
#---------------------------------------------------------------------------
#L'utilisateur a maintenant des choix a faire en plus de mth* : type de guidage, et "rea"
# Alors c'est plus facile d'editer&modifier le script, puis lancer avec ./era2gcm.sh, que de donner tous les params
# TODO check w/ Adriana if we can remove those and put them as inline args (above)
while (($# > 0))
   do
   case $1 in
     "-h") cat <<........fin
           ./era2gcm.sh [-mthini initial_month] [-mthend final_month] [-grid_dir directory_containing_grille_gcm.nc]
........fin
     exit ;;
     "-grid_dir") GRID_DIR=$2 ; shift ; shift ;;
     "-mthini") mth_i=$2 ; shift ; shift ;;
     "-mthend") mth_f=$2 ; shift ; shift ;;
     *) $0 -h ; exit 1
   esac
done
#--Fin du bloc a examiner --------------------------------------------

tmin=1
resol=grilles_gcm.nc

GRID_FI=${GRID_DIR}/${resol}
if [ ! -f "$GRID_FI" ] ; then
   echo "Le fichier $GRID_DIR/$resol est nécessaire; créer le fichier $GRID_FI avec grilles_gcm_netcdf.e"
   exit 1
fi
mth=$mth_i


#####################################################################
#  LOOP ON MONTHS
#####################################################################
while (( mth <= mth_f )) ; do

   echo "mth $mth"
   mois=$(echo "$mth" | cut -c 5-)
   an=$(echo "$mth" | cut -c -4)
   ndays=( 31 28 31 30 31 30 31 31 30 31 30 31 )
   months=( jan feb mar apr may jun jul aug sep oct nov dec )
   if [ $(( an % 4 )) = 0 ] ; then ndays[1]=29 ; fi
   imois=$(( ${mois#0} - 1 ))
   month=${months[$imois]}
   nday=${ndays[$imois]}
   tmax=$(( nday * 4 ))
   echo "PARAMETRES CALENDAIRES $imois $month $nday $tmax"


   iip1=$(ncdump -h "$GRID_FI" | grep lonu | head -1 | awk ' { print $3 } ')
   jjm=$(ncdump -h "$GRID_FI" | grep latv | head -1 | awk ' { print $3 } ')
   (( jjp1 = jjm + 1 ))
#   \rm t2.nc ua.nc va.nc sst.nc u.nc v.nc T.nc ts.nc

#####################################################################
# Choix de la periode temporelle
#####################################################################

   t0="l=$tmin"
   t1tn="l=${tmin}:${tmax}"

#####################################################################
# Lien avec les fichiers netcdf contenant les d0 ECMWF 
#####################################################################
   echo "-------- liens de telechargement a actualiser ----"
   if [ "$rea" = "ERA5" ] ; then
     if [[ $an -ge 2022 ]] ; then
      ANA_DIR="$ERA5_PATH/NETCDF/GLOBAL_025/hourly"
      suf="ap1e5.GLOBAL_025"
     else
      ANA_DIR="$ERA5_PATH/NETCDF/GLOBAL_025/4xdaily"
      suf="aphe5.GLOBAL_025"
     fi
   elif [ "$rea" = "ERAI" ] ; then
      ANA_DIR="$ERAI_PATH/NETCDF/GLOBAL_$resol_rea/4xdaily"
      suf="aphei.GLOBAL_$resol_rea"
   fi

   if [ ! -d $ANA_DIR ] ; then echo Directory $ANA_DIR does not exist ; exit 1 ; fi

   ########################################################################
   # Loop on variables among u, v, ta, q
   ########################################################################

   for var in $vars ; do

     case $var in
         ta) filename=T.nc ;;
         q) filename=hur.nc ;;
         *) filename=$var.nc
     esac
     outd=GUIDE_${rea}/$an/$mois
     out_file=$outd/$filename

     if [ ! -f $out_file ] ; then
        mkdir -p $outd
        file_rea="$ANA_DIR/AN_PL/$an/$var.$an$mois.$suf.nc"

        ###################################################################
        # Automatically downloading reanalysis if needed
        ###################################################################
        if [ "$( echo $ERAI_PATH | grep 3DInputData )" != "" ] ; then
             if [ ! -f $file_rea ] ; then
                mkdir -p $( dirname $file_rea )
                cd $( dirname $file_rea )
                wget http://lmdz.lmd.jussieu.fr/pub/3DInputData/$( echo $file_rea | sed -e 's/^.*3DInputData//' )
                cd -
             fi
         fi
         ###################################################################
         # Checking the avaibility of reanalysis native file
         ###################################################################
         if [ ! -f $file_rea ] ; then echo Reanalysis file $file_rea missing ; exit 1 ; fi

         ###################################################################
         # Special treatments
         ###################################################################
         if [ "$rea" = "ERAI" ] ; then
             # original data in "short" should be changed to "float" for ferret
             ncap2 -s $var'=float('$var')' $file_rea -O tmp.nc
         elif [ "$rea" = "ERA5" -a $an -ge 2022 ] ; then
             # Recent analysis available on a daily basis
             cdo selhour,0,6,12,18 $file_rea -O tmp.nc
         else
             ln -sf $file_rea tmp.nc
         fi

         ###################################################################
         # Dimensions of horizontal grid
         ###################################################################
         case $var in
            v) imjm="i=1:$iip1,j=1:$jjm" ;;
            *) imjm="i=1:$iip1,j=1:$jjp1"
         esac

         ###################################################################
         # Grid to be used from grilles_gcm.nc
         ###################################################################
         case $var in
            u|v) grid=grille_$var ;;
            *) grid=grille_s
         esac

         ###################################################################
         # Interpolating with ferret
         ###################################################################
         cat <<.........eod......... >| tmp.jnl
         ! NB : Augmenter la memoire (plus de 512) peut faire planter
         set memory/size=512
         use "$GRID_FI"
         use tmp.nc
         define axis/t="1-${month}-${an}:00:00":"${nday}-${month}-${an}:18:00":6/units=hours thour
         ! Pour regrid horizontal on utilise la variable grille_s(lonv,latu) du fichier grilles_gcm.nc
         !! Alors il faut renommer la variable à la fin (ncrename), car le code cherche "UWND", "VWND".
         save/clobber/file="$out_file" $var[d=2,gxy=${grid}[d=1],$imjm,$t0,gt=thour@asn]
         repeat/$t1tn save/file="$out_file"/append $var[d=2,gxy=${grid}[d=1],$imjm,gt=thour@asn]
.........eod.........

         ferret -nojnl <<.........eod.........
         go tmp.jnl
         quit
.........eod.........

        ###################################################################
        # Changing variable names
        ###################################################################
         case $var in
            u) out_var=UWND ;;
            v) out_var=VWND ;;
            r) out_var=RH ;;
            ta) out_var=AIR
         esac
         # ferret a ecrit $varu en majuscules,
         # l'equivalent en bash est ${varu^^} 
         # (Note : inversement, ${varu,,} passe $varu de majuscules
         # en minuscules)
         ncrename -v ${var^^},$out_var $out_file
     fi
   done


   #########################################################################
   # Updating month counter
   #########################################################################
   echo AN MTH $an $mois
   (( mth = $mth + 1 ))
   if [ $mois = 12 ] ; then
      (( an = $an + 1 ))
      mth=${an}01
   fi

done
ln -sf GUIDE_$rea GUIDE
