#!/bin/bash
###############################################################################
# This script is the command that is executed every run.
# Check the examples in examples/
#
# This target-runner is run in the execution directory (execDir, --exec-dir).
#
#
# PARAMETERS:
# $1 is the candidate number
# $2 is the instance ID
# $3 is the seed
# $4 is the instance name
# The rest ($* after `shift 4') are parameters to the run
#
# RETURN VALUE:
# This script should print one numerical value: the cost that must be minimized.
# Exit with 0 if no error, with 1 in case of error
###############################################################################
error() {
    echo "`TZ=UTC date`: $0: error: $@"
    exit 1
}

EXE=matlab
FIXED_PARAMS="-nosplash -nodesktop -nodisplay"

CANDIDATE=$1
INSTANCEID=$2
SEED=$3
INSTANCE=$4
shift 4 ||  error "Not enough parameters"
CAND_PARAMS=$*

STDOUT=c${CANDIDATE}-${INSTANCEID}-${SEED}.stdout
STDERR=c${CANDIDATE}-${INSTANCEID}-${SEED}.stderr

## If the program just prints a number, we can use 'exec' to avoid
## creating another process, but there can be no other commands after exec.
#exec $EXE ${FIXED_PARAMS} -i $INSTANCE ${CAND_PARAMS}
#exit 1

## Otherwise, save the output to a file, and parse the result from it.
## (If you wish to ignore segmentation faults you can use '{}' around
## the command.)
## This example assumes that CAND_PARAMS contains something like "A=10 B=5"
$EXE ${FIXED_PARAMS} -r "INSTANCE=${INSTANCEID};SEED=${SEED};${CAND_PARAMS// /;};RUN(INSTANCE,A,B);exit" < RUN.m 1> ${STDOUT} 2> ${STDERR}

## 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

if [ -s "${STDOUT}" ]; then
    COST=$(cat ${STDOUT} | grep 'Result for irace=' | cut -f2 -d '=')
    echo "$COST"
    rm -f "${STDOUT}" "${STDERR}"
    exit 0
else
    error "${STDOUT}: No such file or directory"
fi
