#!/bin/bash
set -eu  # exit on most (not all!) error codes, and error on unset variables
export LC_ALL=C # set locale for computation with awk

######################################################################
# Author : Najda Villefranque
# 2025/02/04
# Running automatically a series of SCM experiments with MESONH
# Launched from HighTune/bench.sh
# uses dephy-scm and dephy-mnh to generate namelists
# Inspired from serie_LMDZ.sh
######################################################################

local=$(pwd)
install_dir=$local/../../../install_shared

# I need to interact with Fleur to make sure the output format is the right
# one...
py_convert_script=convertMNH570_to_DEPHY_SCM_microphys_chaude_froide_sans_budget.py
py_convert_script=convert_MNH571_to_DEPHY

mode=SCM

# various MESONH config variables are in env_MESONH.profile
source $install_dir/env_MESONH.profile
echo $DEPHY_SCM_DIR
if [ ! -d $MNH_DIR ] ; then 
  echo error: $MNH_DIR does not exist. 
  echo Problem occured during MNH installation?
  exit 1
fi

######################################################################
# Reading arguments
######################################################################
if [[ $# -lt 1 ]] ; then
   echo "run on $local"
   bash serie_MESONH.sh --help
   exit 1
fi

debug=0
nproc=$(( $(lscpu  -e=core | wc -l) - 1 ))               # logical threads 
nproc=$(( $(lscpu  -e=core | sort | uniq | wc -l) - 1 )) # physical computing units
nproc_=$nproc
while (( $# > 0 )) ; do
  case $1 in
    -nproc) nproc_=$2; shift; shift ;;
    -debug) debug=1; shift ;;
    -h|-help|--help) echo Usage: $0 "[-debug] [- CASE1/SUBCASE1 [CASE2/SUBCASE2 ...] wave_number" ; exit 1 ;;
    *)      listecas=${*:1:$#-1} # all but last arguments
            WAVEN=${*: -1}       # last arg
            shift $#
  esac
done

# clamp user required nproc to available number of procs
if [ $nproc_ -lt $nproc ] ; then nproc=$nproc_ ; fi

echo "listecas $listecas wave $WAVEN"
EXPE=$(realpath "$local/WAVE$WAVEN")

if [[ $debug = 1 ]] ; then set -vx ; fi

######################################################################
# Various checks
######################################################################

if [[ ! -d $MNH_DIR ]]; then
   echo "Directory $MNH_DIR does not exist. Please modify variable \$MNH_DIR"
   exit 1
fi

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

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

##################################################################
# I. Getting parameter generated by the latin hypercube sampling #
##################################################################
if [[ ! -f $EXPE/Par1D_Wave$WAVEN.asc ]] ; then
  echo "File $EXPE/Par1D_Wave$WAVEN.asc does not exist."
  echo "Please modify variable \$EXPE or run param2R.sh or param2Rwave.sh on directory $EXPE"
  exit 1
fi

sed -e 's/\"//g' "$EXPE/Par1D_Wave$WAVEN.asc" >| param.asc
param_file=$(realpath param.asc)
nl=$(wc -l param.asc | awk ' { print $1 } ')

# Stopping here if no case to be done
echo $listecas
if [[ "$listecas" = "" ]] ; then echo "No case to be run" ; exit 0 ; fi

####################################
# II. Loop on cases and PPE members 
####################################

## helper function to run MESONH
run_mesonh_cassouscasexp() {
  # cassouscas eg ARMCU/MESONH
  # proc eg /p1 to isolate each processor 
  mkdir -p $MNH_DIR/MY_RUN/htexplo/$cassouscas$proc
  cd $MNH_DIR/MY_RUN/htexplo/$cassouscas$proc
  ln -sf $EXPE/namelists/conf_PRE_IDEA_${cas}_${souscas}_$mode.nam$exp PRE_IDEA1.nam
  ln -sf $EXPE/namelists/conf_EXSEG00_${cas}_${souscas}_$mode.nam$exp EXSEG1.nam
  cp $EXPE/../run_mesonh.sh .
  #cp $EXPE/../$py_convert_script .
  cp $DEPHY_MNH_DIR/scripts_mnh/$py_convert_script .
  bash run_mesonh.sh
  res=$(ls -1rt *000*.nc|tail -1)
  python $py_convert_script -f -i $res
  res=${res%.nc}_dephy.nc
  mkdir -p $EXPE/$cassouscas
  if [ -u $exp ] ; then 
    fil=CTRL.nc
  else
    fil=${exp:1}.nc
  fi
  cp $res $EXPE/$cassouscas/$fil
  if [ $? -ne 0 ] ; then 
    echo $0 failed for $cassouscas $exp
    exit 1
  fi
}

for cassouscas in $listecas ; do
  cas=$(echo $cassouscas|cut -d / -f 1)
  souscas=$(echo $cassouscas|cut -d / -f 2)
  echo $cas/$souscas

  ######
  # II.1 Generate namelists

  cd $DEPHY_SCM_DIR
  source setenv
  cd $cassouscas
  python driver_DEF.py

  cd $DEPHY_MNH_DIR/scripts_convert/
  opts=
  case $cas in 
    ARMCU|FIRE|RICO) opts=$opts" -g ../grilles/grille_AROME_CL.txt" ;;
    BOTANY) opts=$opts" -g ../grilles/grille_BOTANY_4km.txt -a 4 -S ECUME6" ;; # Botany grid, with Adrien Marcel version
    *) opts=$opts" -g ../grilles/grille_AROME.txt" ;;
  esac
  case $cassouscas in
    ARMCU/MNHRADSURF) opts=$opts" -M"  # with MOSAI surface
      ;;
  esac
  python convert.py -c $cas -s $souscas -i $DEPHY_SCM_DIR -o $EXPE/namelists/ -P $param_file $opts -m $mode

  ######
  # II.2 run default / CTRL experiment

  exp=
  proc="/p1"
  run_mesonh_cassouscasexp

  ######
  # II.3 run all experiments from the PPE

  iproc=0
  for exp in $(ls $EXPE/namelists/conf*PRE*${cas}_${souscas}_$mode.nam_*SCM*|sed -e "s/.*.nam//g")
  do
    if [ $iproc -lt $nproc ]; then
      iproc=$(($iproc+1))
    else
      wait
      iproc=1
    fi
    proc="/p$iproc"

    case $cassouscas in 
      ARMCU/MNHRAD) # !!! (this is bad coding, I know I should not do that) !!!
        # Rad Ts not in namelist but in forcings... hack the namelists 
        mnhnam=$EXPE/namelists/conf_EXSEG00_${cas}_${souscas}_$mode.nam$exp
        names=( $(head -1 $param_file | sed -e "s/t_IDs //g" -e 's/\"//g' -e 's/lp/(/g' -e 's/rp/)/g') )
        vals=( $(grep ${exp:1} $param_file| sed -e "s/${exp:1} //g") )
        nparams=${#vals[*]} 
        ip=0
        while [ $ip -lt $nparams ] ; do
          name_i=${names[$ip]}
          val_i=${vals[$ip]}
          ip=$(($ip+1))
          sed_i "s/$name_i.*=.*$/$name_i = $val_i,/g" $mnhnam
        done
        ;;
    esac
    
    run_mesonh_cassouscasexp &
  done

  wait
done #Loop on SCM cases
