#!/bin/bash
###############################################################################
# This hook is run for each candidate to evaluate it after all
# candidate configurations have been run on a single instance.
#
# Check the examples in examples/
#
# PARAMETERS:
# $1 is the instance name
# $2 is the candidate number
# $3 is the total number of candidates alive in this iteration
#
# RETURN VALUE:
# This hook should print one numerical value: the cost that must be minimized.
# Exit with 0 if no error, with 1 in case of error
###############################################################################
INSTANCE=$1
CANDIDATE=$2
TOTALCANDIDATES=$3

STDOUT=c${CANDIDATE}.stdout
STDERR=c${CANDIDATE}.stderr

error() {
    echo "`TZ=UTC date`: error: $@"
    exit 1
}

# # This may be used to introduce a delay if there are filesystem
# # issues.
# SLEEPTIME=1
# while [ ! -s "${STDOUT}" ]; do
#     sleep $SLEEPTIME
#     let "SLEEPTIME += 1"
# done

# This is an example of reading a number from the output of
# hook-run. It assumes that the objective value is the first number in
# the first column of the only line starting with a digit.
if [ -s "${STDOUT}" ]; then
    COST=$(cat ${STDOUT} | grep -e '^[[:space:]]*[+-]\?[0-9]' | cut -f1)
    echo "$COST"
    rm -f "${STDOUT}" "${STDERR}"
    exit 0
else
    error "${STDOUT}: No such file or directory"
fi
