#!/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"

# check if the list exist
if [ ! -f "${LISTFILE}" ]; then
  echo "ERROR: No traces of a setup_jobs run found!"; exit 1
fi

# read the job ids
readarray -t JOBIDS < <(cat "${LISTFILE}")

# get job details
get_job_details () {
  echo "$(sacct --allocations --parsable --format "JobID,User,TimelimitRaw,Partition,AllocNodes,AllocCPUS,State" --jobs $1)"
}
STRING_TIME="$(get_job_details ${JOBIDS[0]})"
STRING_HOLD="$(get_job_details ${JOBIDS[1]})"
STRING_KILL="$(get_job_details ${JOBIDS[2]})"

# set expected details
EXPECTED_TIME="JobID|User|TimelimitRaw|Partition|AllocNodes|AllocCPUS|State|
${JOBIDS[0]}|${USER}|60|dev|1|2|COMPLETED|"

EXPECTED_HOLD="JobID|User|TimelimitRaw|Partition|AllocNodes|AllocCPUS|State|
${JOBIDS[1]}|${USER}|10|small_shared|1|2|COMPLETED|"

EXPECTED_KILL="JobID|User|TimelimitRaw|Partition|AllocNodes|AllocCPUS|State|
${JOBIDS[2]}|${USER}|15|dev|1|2|CANCELLED by ${UID}|"

# compare solution and expected configuration
if ! diff <(echo -e "$EXPECTED_TIME") <(echo -e "$STRING_TIME") > /dev/null; then
  echo "ERROR: Job results for the 'update time' step not as asked for!"; exit 1
fi
if ! diff <(echo -e "$EXPECTED_HOLD") <(echo -e "$STRING_HOLD") > /dev/null; then
  echo "ERROR: Job results for the 'release the job!' step not as asked for!"; exit 1
fi
if ! diff <(echo -e "$EXPECTED_KILL") <(echo -e "$STRING_KILL") > /dev/null; then
  echo "ERROR: Job results for the 'kill the job!' step not as asked for!"; exit 1
fi

echo "Congratulations! Task solved correctly!"

# exit the script with zero exit code
exit 0
