#!/bin/bash
### Partition to use
#SBATCH --account=cin0391
#SBATCH --constraint=GENOA
### Number of nodes/cores to use
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=24
#SBATCH --cpus-per-task=8
#SBATCH --threads-per-core=1 # --hint=nomultithread
### Job information
#SBATCH --job-name=jobPCM0
#SBATCH --output=jobPCM_%j.out
#SBATCH --time=4:00:00

########################################################################
# Modify here the parameters depending on your setup
####################################################
# Path to the arch.env to source:
source ../trunk/LMDZ.COMMON/arch.env

# Number of threads to use (must be the same as "#SBATCH --cpus-per-task=" above)
export OMP_NUM_THREADS=$SLURM_CPUS_PER_TASK
export OMP_STACKSIZE=400M

# Name of executable for the PCM:
exePCM="gcm_64x48x32_phymars_para.e"

# Execution command:
exe_cmd="srun --ntasks-per-node=${SLURM_NTASKS_PER_NODE} --cpu-bind=none --mem-bind=none --label -- ./adastra_cpu_binding.sh ./$exePCM"
########################################################################


ulimit -s unlimited

# Running the PCM
read i_year n_year r_plnt2earth_yr iPCM iPEM nPCM nPCM_ini < launchPEM.info
echo "Run \"PCM $iPCM\" is starting."
cp run_PCM.def run.def
eval "$exe_cmd > run.log 2>&1"
if [ ! -f "restartfi.nc" ] || ! (tail -n 100 run.log | grep -iq "everything is cool!"); then # Check if it ended abnormally
    echo "Error: the run \"PCM $iPCM\" crashed!"
    if [ $mode -ne 0 ]; then
        echo "Be careful: there may be dependent jobs remaining in the queue! You can cancel them by executing the script \"kill_launchPEM.sh\"."
    fi
    exit 1
fi

# Copy data files and prepare the next run
mv run.log logs/runPCM${iPCM}.log
if [ -f "diagfi.nc" ]; then
    mv diagfi.nc diags/diagfi${iPCM}.nc
fi
if [ -f "diagsoil.nc" ]; then
    mv diagsoil.nc diags/diagsoil${iPCM}.nc
fi
if [ -f "stats.nc" ]; then
    mv stats.nc diags/stats${iPCM}.nc
fi
k=0
if [ $(echo "$k > 0" | bc) -eq 1 ]; then # Only the last 2 years are taken for the PEM
    cp Xoutdaily4pem.nc Xoutdaily4pem_Y${k}.nc
    cp Xoutyearly4pem.nc Xoutyearly4pem_Y${k}.nc
fi
mv Xoutdaily4pem.nc diags/Xoutdaily4pem${iPCM}.nc
mv Xoutyearly4pem.nc diags/Xoutyearly4pem${iPCM}.nc
cp restartfi.nc starts/restartfi${iPCM}.nc
mv restartfi.nc startfi.nc
if [ -f "restart.nc" ]; then
    cp restart.nc starts/restart${iPCM}.nc
    mv restart.nc start.nc
elif [ -f "restart1D.txt" ]; then
    cp restart1D.txt starts/restart1D${iPCM}.txt
    mv restart1D.txt start1D.txt
fi
((iPCM++))
sed -i "1s/.*/$i_year $n_year $r_plnt2earth_yr $iPCM $iPEM $nPCM $nPCM_ini/" launchPEM.info
