#!/bin/bash

# exit this script if any error occurs
set -e

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

# get newest fitting solution file
SOLUTION_FILE="${SCRIPTDIR}/$(cd "${SCRIPTDIR}"; ls -At my_first_job_*.out 2>/dev/null | head -n 1)"
if [ ! -f "${SOLUTION_FILE}" ]; then
  echo "ERROR: No output file found!"
  exit 1
fi

# get job id
JOBID="$(grep '^JobId=' "${SOLUTION_FILE}" | cut -d ' ' -f 1 | 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 --format "JobID,User,TimelimitRaw,Partition,AllocNodes,AllocCPUS,State" --jobs $JOBID)"

EXPECTED_CONFIG="JobID|User|TimelimitRaw|Partition|AllocNodes|AllocCPUS|State|
${JOBID}|${USER}|10|small_shared|2|32|COMPLETED|"

# compare solution and expected configuration
diff <(echo -e "$EXPECTED_CONFIG") <(echo -e "$STRING") > /dev/null \
  && echo "Congratulations! Task solved correctly!" \
  || echo "ERROR: Job configuration not as asked for!"

# exit the script with zero exit code
exit 0
