#!/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 a single numerical value
###############################################################################
INSTANCE=$1
CANDIDATE=$2
TOTALCANDIDATES=$3

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

error() {
    echo "`TZ=UTC date`: error: $@"
    if [ -s error.log ]; then
        cat error.log
    fi
    exit 1
}

error_sleep() {
    echo "`TZ=UTC date`: error: $@" >> error.log
    sleep 60
}

calc_measure() {
    # A program that normalizes all _dat files to [0, 1]
    # (optional, not included).
    ~/bin/normalize *_dat || error "normalizing failed"
    # A program for computing the hypervolume. Download hypervolume
    # code from http://iridia.ulb.ac.be/~manuel/hypervolume
    ~/bin/hv --quiet -r "1.1 1.1" *_dat -s "_hv" || error "calculating hypervolume failed"
}


cd arena || error "cannot change to directory 'arena'"

while ! ls *.stdout_dat &> /dev/null ; do
    NUM=$(ls -1 *.stdout 2> /dev/null | wc --lines)
    if [ "$NUM" -ne "$TOTALCANDIDATES" ]; then
        error_sleep "only found $NUM files out of $TOTALCANDIDATES"
        continue
    fi
    # Check every STDERR
    for FILENAME in *.stdout; do
        FILESTDERR=${FILENAME/stdout/stderr}
        [ OK = "$(cat ${FILESTDERR})" ] || (error_sleep "${FILESTDERR} is not OK"; continue)
        [ -s "$FILENAME" ] || (error_sleep "$FILENAME is empty"; continue)
        # Or do some transformation like selecting some columns.
        cat $FILENAME > ${FILENAME}_dat
    done
    calc_measure
    rm -f error.log
done

if [ -s "${STDOUT}_dat_hv" ]; then
    COST=$(cat "${STDOUT}_dat_hv" | grep -e '^[0-9]' | cut -f1)
    # Negative because hypervolume is maximised but irace minimises.
    echo "-$COST"
    rm -f c${CANDIDATE}.*
    exit 0
else
    error "${STDOUT}_dat_hv: No such file or directory"
fi
