#!/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 files
get_sol_file () {
  DIR="$1"; NAME="$2"
  SOLUTION_FILE="${DIR}/$(cd "${DIR}"; ls -At ${NAME}_*[0-9].out 2>/dev/null | head -n 1)"
  if [ ! -f "${SOLUTION_FILE}" ]; then
    echo "ERROR: No $NAME file found!"; exit 1
  fi
  echo "${SOLUTION_FILE}"
}
SOLUTION_FILEA="$(get_sol_file "${SCRIPTDIR}/resultA" "jobA")"
SOLUTION_FILEB="$(get_sol_file "${SCRIPTDIR}/resultB" "jobB")"

# get job id
get_job_id () {
  FILE="$1"; NAME="$2"
  JOBID="$(grep -m 1 '^JobId=' "${FILE}" | cut -d ' ' -f 1 | cut -d '=' -f 2)"
  if [ -z "${JOBID}" ]; then
    echo "ERROR: No job id found in results file!" 1>&2; exit 1
  fi
  echo $JOBID
}
JOBIDA=$(get_job_id "$SOLUTION_FILEA" "jobA")
JOBIDB=$(get_job_id "$SOLUTION_FILEB" "jobB")

# get job details
get_job_details () {
  echo "$(sacct --allocations --parsable --format "JobID,User,TimelimitRaw,Partition,AllocNodes,AllocCPUS,State" --jobs $1)"
}
STRINGA="$(get_job_details $JOBIDA)"
STRINGB="$(get_job_details $JOBIDB)"

# set expected details
EXPECTED_CONFIGA="JobID|User|TimelimitRaw|Partition|AllocNodes|AllocCPUS|State|
${JOBIDA}|${USER}|15|dev|1|32|COMPLETED|"

EXPECTED_CONFIGB="JobID|User|TimelimitRaw|Partition|AllocNodes|AllocCPUS|State|
${JOBIDB}|${USER}|15|small_shared|4|128|COMPLETED|"

# compare solution and expected configuration
if ! diff <(echo -e "$EXPECTED_CONFIGA") <(echo -e "$STRINGA") > /dev/null; then
  echo "ERROR: Job configuration A not as asked for!"; exit 1
fi
if ! diff <(echo -e "$EXPECTED_CONFIGB") <(echo -e "$STRINGB") > /dev/null; then
  echo "ERROR: Job configuration B not as asked for!"; exit 1
fi

echo "Congratulations! Task solved correctly!"

# exit the script with zero exit code
exit 0
