#!/bin/bash

# exit this script if any error occurs
set -e

# get the directory where this script is in
SCRIPTDIR="$(realpath -s $(dirname $0))"

# the job id list file in order to only kill and monitor jobs of this task
LISTFILE="${SCRIPTDIR}/job_list.dat"

# killing old jobs of the job id list file
if [ -f "${LISTFILE}" ]; then
  scancel --quiet $(paste -s -d ' ' "${LISTFILE}") && rm "${LISTFILE}"
fi
touch "${LISTFILE}"

# create the jobs
sbatch --parsable --time=1-00:00:00 --partition=dev --job-name="i_need_less_time" "${SCRIPTDIR}/job_script.sbatch" >> "${LISTFILE}"

sbatch --parsable --time=10:00 --partition=small_shared --hold --job-name="i_am_ready_to_go" "${SCRIPTDIR}/job_script.sbatch" >> "${LISTFILE}"

TMPFILE=$(mktemp)
salloc --no-shell --nodes=1 --ntasks-per-node=1 --time=15:00 --partition=dev --job-name="just_end_me" 2> "$TMPFILE"
grep -m 1 'job allocation' "$TMPFILE" | cut -d ' ' -f 5 >> "${LISTFILE}"
rm "$TMPFILE"

# exit the script with zero exit code
exit 0
