#!/bin/bash

# exit this script if any error occurs
set -e

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

# define solution
SOLUTION_FILE="${SCRIPTDIR}/my_results.txt"

# check if the solution file exists
if [ ! -f "${SOLUTION_FILE}" ]; then
  echo "ERROR: No results file not found!"
  exit 1
fi

# check if on compute node
HOST="$(hostname)"
if [[ $HOST = node* ]]; then
  echo "ERROR: Please execute this script when you are back on the login node!"
  exit 1
fi

# get job id
JOBID="$(grep 'SLURM_JOB_ID' "${SOLUTION_FILE}" | cut -d '=' -f 2)"
if [ -z "${JOBID}" ]; then
  echo "ERROR: No job id found in results file!"
  exit 1
fi

# get job details
STRING=$(sacct --allocations --parsable --jobs $JOBID | tail -n 1)

# check if only 2 CPUS had been used
if [ "$(echo "${STRING}" | cut -d '|' -f 5 )" != "2" ]; then
  echo "ERROR: You used more CPUs than asked for (1 node has only 2 CPUs by default)!"
  exit 1
fi

# check if job has been completed
if [ "$(echo "${STRING}" | cut -d '|' -f 6 )" != "COMPLETED" ]; then
  echo "ERROR: Job has not been closed successfully!"
  exit 1
fi

# done
echo "Congratulations! Task solved correctly."

# exit the script with zero exit code
exit 0
