#!/bin/bash
#
# This script prepare the nsimus config3D files for ARPEGE (=param files)
# and write the script that install and launch the 3D simulation with Eclis
#
# Romain Roehrig and Maelle Coulon-Decorzens - Aout 2026
#
#########################################################################"

njobs=50 #number of job that are launch in the same time
group=TUNARP/V74 #to manage 3D simulation pathways


if [ $# -lt 3 ] ; then
    bash prep3D.sh --help
    exit 1 
fi

while (( $# > 0 )) ; do
    case $1 in
        -wave)  wave=$2 ;  shift ; shift ;;
        -config3D)  config3D=$2 ; shift ; shift ;;
        -nsimus)  nsimus=$2 ; shift ; shift ;;
        -h|-help|--help) echo Usage: $0 "[-wave wave_number] [-config3D config / parameter reference files to run 3D ARPEGE simulation] [-nsimus nsimus]" ; exit 1 ;;
        *) echo the args $1 in not an argument of this script ; exit 1 ;; 
    esac
done


#    Preparing the 3D config files
###################################

cd WAVE${wave}/config3D/

name=$(echo ${config3D} | awk -F'/' '{print $NF}' | awk -F_ '{for(i=2;i<=NF;i++) printf "%s%s", $i, (i<NF?"_":"")}')_W${wave}
nchaine=$(($nsimus - $njobs))
nameconfig3D=param_${name}

cp ../../$config3D .

echo wave $wave config3D $config3D nsimus $nsimus 
echo name $name njobs $njobs nchaine $nchaine 

for i in `seq 1 $nchaine`
do

  run=$(printf "%03d" $i)
  n=$(( i + njobs ))
  n=$(printf "%03d" $n)

  cp $config3D toto
  sed s/'wave=.*'/'wave='$wave/ toto > tata
  sed s/'XXX'/$run/g tata > toto
  sed s/'ZZZ'/$n/g toto > ${nameconfig3D}_r$run
  chmod u+x ${nameconfig3D}_r$run
  rm -f toto tata
done

for i in `seq $(($nchaine + 1))  $nsimus`
do

  run=$(printf "%03d" $i)

  cp $config3D toto
  sed s/'wave=.*'/'wave='$wave/ toto > tata
  sed s/'NEXTEXP=.*'// tata > toto
  sed s/'XXX'/$run/g toto > ${nameconfig3D}_r$run
  chmod u+x ${nameconfig3D}_r$run

  rm -f toto tata
done

cd ../../ #back in wordir

# Write the install_and_run3D_wave$wave.sh script
#################################################

pathrelan=$(pwd | sed "s|\(.*$USER\).*|\1|")/relances
echo pathrelan $pathrelan 

cat << eod > install_and_run3D_wave${wave}.sh
bash install_and_run3D.sh -wave $wave -nsimus $nsimus -njobs $njobs -name ${name} -group ${group}/WAVE${wave} -pathrelan $pathrelan
eod

echo YOU CAN LAUNCH install_and_run3D_wave${wave}.sh script in the workdir !
