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

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

# Name of executable for the PEM:
exePEM="pem_64x48x32_phymars_seq.e"

# Argument for the PEM execution ("--auto-exit" for SLURM and PBS/TORQUE | "" when the script is not run as a job):
arg_pem="--auto-exit"
########################################################################


ulimit -s unlimited

# Running the PEM
read i_year n_year r_plnt2earth_yr iPCM iPEM nPCM nPCM_ini < launchPEM.info
echo "Run \"PEM $iPEM\" is starting."
cp run_PEM.def run.def
eval "./$exePEM $arg_pem > run.log 2>&1"
if [ ! -f "restartfi.nc" ] || ! (tail -n 100 run.log | grep -iq "so far, so good!"); then # Check if it ended abnormally
    echo "Error: the run \"PEM $iPEM\" crashed!"
    exit 1
fi

# Copy data files and prepare the next run
mv run.log logs/runPEM${iPEM}.log
if [ -f "diagevol.nc" ]; then
    mv diagevol.nc diags/diagevol${iPEM}.nc
fi
if [ -f "diagevol_soil.nc" ]; then
    mv diagevol_soil.nc diags/diagevol_soil${iPEM}.nc
fi
cp restartpem.nc starts/restartpem${iPEM}.nc
mv restartpem.nc startpem.nc
cp restartfi.nc starts/restartfi_postPEM${iPEM}.nc
mv restartfi.nc startfi.nc
if [ -f "restart.nc" ]; then
    cp restart.nc starts/restart_postPEM${iPEM}.nc
    mv restart.nc start.nc
elif [ -f "restart1D.txt" ]; then
    cp restart1D.txt starts/restart1D_postPEM${iPEM}.txt
    mv restart1D.txt start1D.txt
fi

# Launch the next cycle
#if [ "$(awk 'END{print $NF}' launchPEM.info)" -eq 7 ]; then
#    read i_year n_year r_plnt2earth_yr iPCM iPEM nPCM nPCM_ini < launchPEM.info
#    ./launchPEM.sh cont # Continue the PEM run if it stopped because of job time limit
#else
    ./launchPEM.sh new
#fi
