#!/bin/bash
#SBATCH --job-name=run_year1
#SBATCH --account=cin0391
#SBATCH --constraint=GENOA
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=24
#SBATCH --cpus-per-task=8
#SBATCH --threads-per-core=1 # --hint=nomultithread
#SBATCH --exclusive
#SBATCH --output=run_year1_%A.out
#SBATCH --time=16:00:00

## Script to run chained simulations
## (uses script "run0" and reference file "run.def.ref")
## Set values of "num_now" and "num_end" in the script below
## to set initial year # and final year # of the simulation

# A few parameters that might need be changed 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
#
########################################################################
set -exv
ls -al
trap 'echo -e "Error at line $LINENO!"' ERR

# Set starting year and ending year below:
num_now=1
num_end=10
num_previous=$(( num_now - 1 ))

echo "$num_previous" > num_run
# next year number
num_next=$(( num_now + 1 ))

# Check if required files exist
\rm -f  error; touch error

if [ ! -f run.def.ref ]; then
  echo "Error: file \"run.def.ref\" not found in current directory!" > error
  exit 1
fi

if [ ! -x run0 ]; then
  echo "Error: file \"run0\" not found or not executable in current directory!" > error
  exit 1
fi

if [ ! -f run_year$num_now ]; then
  echo "Error: file \"run_year${num_now}\" not found in current directory!" > error
  exit 1
fi

# Run model for a year (669 sols)
sed s/9999/669/ run.def.ref > run.def ; ./run0 >> error

# Launch job for next year
if (( num_next <= num_end )) ; then
  cp -f run_year$num_now tmp
  sed -e "s@run_year${num_now}@run_year${num_next}@" \
      -e "s@num_now=${num_now}@num_now=${num_next}@" tmp > run_year$num_next
  rm tmp
  sbatch run_year$num_next
fi
