#!/bin/bash
########################################################################
#### Launching script for a chained simulation of PEM and PCM runs  ####
########################################################################
# This script can take an argument:
#   - If there is no argument, then the script initiates a PEM simulation from scratch.
#   - If the argument is 're', then the script relaunches an existing PEM simulation.
#     It will ask for parameters to know the starting point that you want to. 
########################################################################
set -e
trap 'echo -e "\033[31mError: an issue occurred in the script on line $LINENO! Please review the command and try again.\033[0m"' ERR


########################################################################
# Modify here the parameters for the simulation
###############################################
# Set the number of years to be simulated, either Martian or Earth years (> 0):
n_mars_years=100.
#n_earth_years=300.

# Set the number of initial PCM runs (>= 2):
nPCM_ini=3

# Set the number of PCM runs between each PEM run (>= 2):
nPCM=2

# Set the counting method for the number of years to be simulated (0 = "only PEM runs count"; any other values = "PCM runs are taken into account"):
counting=0

# Set the launching mode (0 = "processing scripts"; any other values = "submitting jobs"). The former option is usually used to process the script on a local machine while the latter is used to submit jobs on a supercomputer with SLURM or PBS/TORQUE:
mode=1
########################################################################


dir=`pwd`
machine=`hostname`
user=`whoami`
if [ ! -f "lib_launchPEM.sh" ]; then
    echo "Error: file \"lib_launchPEM.sh\" does not exist in $dir!"
    echo "It can be found in the PEM deftank."
    exit 1
fi

source lib_launchPEM.sh
export counting mode

if [ $# -eq 0 ]; then
    # Starting from scratch
    echo "The launching script is starting!"
    echo "The output file is \"launchPEM.log\"."
    exec > launchPEM.log 2>&1
    echo "Beginning of the launching script for the PEM simulation."
    date
    checklaunch
    initlaunch
    cyclelaunch $mode $counting $nPCM_ini

else
    # Starting a new cycle
    if [ $1 = "new" ]; then
        exec >> launchPEM.log 2>&1
        echo
        echo "This is a new cycle for the PEM simulation."
        date
        if [ $mode -ne 0 ]; then
            job_scheduler
            if command -v squeue &> /dev/null; then
                unset SLURM_MEM_PER_CPU SLURM_MEM_PER_GPU SLURM_MEM_PER_NODE
            fi
        fi
        read i_myear n_myear convert_years iPCM iPEM nPCM nPCM_ini < info_PEM.txt
        cyclelaunch $mode $counting $nPCM

    # Starting a relaunch
    elif [ $1 = "re" ]; then
        if [ ! -f "info_PEM.txt" ]; then
            echo "Error: file \"info_PEM.txt\" does not exist in $dir!"
            echo "It is necessary to relaunch a PEM simulation."
            errlaunch
        fi
        echo "The relaunch is initialized with a previous successful run to be specified."
        while true; do
            echo "Do you want to relaunch from a 'PCM' or 'PEM' run?"
            read relaunch
            if [ $relaunch = "PCM" ] || [ $relaunch = "PEM" ]; then
                break
            else
                echo "Invalid input. Please enter 'PCM' or 'PEM'."
            fi
        done
        read i_myear n_myear_old convert_years iPCM iPEM nPCM_old nPCM_ini_old < info_PEM.txt
        while true; do
            if [ $relaunch = "PCM" ]; then
                echo "What is the number of the PCM run?"
                echo "It should be between 1 and $(( $((iPCM - 1)) > 1 ? $((iPCM - 1)) : 1 ))."
                read irelaunch
                if [ 1 -le $irelaunch ] && [ $irelaunch -le $(( $((iPCM - 1)) > 1 ? $((iPCM - 1)) : 1 )) ]; then
                    break
                else
                    echo "Invalid input. Please enter a valid PCM run number."
                fi
            else
                echo "What is the number of the PEM run?"
                echo "It should be between 1 and $(( $((iPEM - 1)) > 1 ? $((iPEM - 1)) : 1 ))."
                read irelaunch
                if [ 1 -le $irelaunch ] && [ $irelaunch -le $(( $((iPEM - 1)) > 1 ? $((iPEM - 1)) : 1 )) ]; then
                    break
                else
                    echo "Invalid input. Please enter a valid PEM run number."
                fi
            fi
        done
        exec >> launchPEM.log 2>&1
        echo
        echo "This is a relaunch for the PEM simulation from the run \"$relaunch $irelaunch\"."
        date
        checklaunch
        convertyears
        if [ $nPCM_ini -ne $nPCM_ini_old ]; then
            echo "The number of initial PCM runs has been modified from $nPCM_ini_old to $nPCM_ini."
        fi
        if [ $nPCM -ne $nPCM_old ]; then
            echo "The number of PCM runs between each PEM run has been modified from $nPCM_old to $nPCM."
        fi
        if [ "$(echo "$n_myear != $n_myear_old" | bc)" -eq 1 ]; then
            echo "The number of initial PCM runs has been modified from $n_myear_old to $n_myear."
        fi
        sed -i "1s/.*/$i_myear $n_myear $convert_years $iPCM $iPEM $nPCM $nPCM_ini/" info_PEM.txt
        if [ -f "kill_launchPEM.sh" ]; then
            ./kill_launchPEM.sh
        fi
        if [ $relaunch = "PCM" ]; then
            relaunchPCM $mode $counting
        else
            relaunchPEM $mode $counting
        fi

    # Continuing the PEM run
    elif [ $1 = "cont" ]; then
        exec >> launchPEM.log 2>&1
        echo
        echo "This is a continuation of the previous PEM run."
        date
        submitPEM $mode

    # Default case: error
    else
        echo "Error: given argument '$1' for the launching script is unknown!"
        errlaunch
    fi
fi
