#!/bin/bash
###############################################################################
# This script is the command that is executed every run.
# Check the examples in examples/
#
# This script is run in the execution directory (execDir, --exec-dir).
#
# PARAMETERS:
# $1 is the candidate configuration 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="./fastga"
LOG_DIR="irace_logs"

#FIXED_PARAMS="--problem=0"
#
CONFIG_ID=$1
INSTANCE_ID=$2 
SEED=$3
INSTANCE=$(echo $4 | sed 's/\//\n/g'|tail -n 1)
CROSSOVER_RATE=$5
CROSSOVER_SELECTOR=$6
CROSSOVER=$7
MUTATION_RATE=$8
MUT_SELECTOR=$9
MUTATION=${10}
REPLACEMENT=${11}
POPSIZE=${12}
OFFSPRINGSIZE=${13}
shift 13 || error "Not enough parameters"

INSTANCE_PARAMS=$*
buckets=0
# STDOUT=${LOG_DIR}/c${CONFIG_ID}_i${INSTANCE_ID}_s${SEED}.stdout
# STDERR=${LOG_DIR}/c${CONFIG_ID}_i${INSTANCE_ID}_s${SEED}.stderr
STDOUT="/dev/null"
STDERR="/dev/null"

if [ ! -x "${EXE}" ]; then
    error "${EXE}: not found or not executable (pwd: $(pwd))"
fi

# 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 ${INSTANCE_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.)
cmd="$EXE --problem=${INSTANCE} --instance=${INSTANCE} --seed=${SEED} ${CROSSOVER_RATE} ${CROSSOVER_SELECTOR} ${CROSSOVER} ${MUTATION_RATE} ${MUT_SELECTOR} ${MUTATION} ${REPLACEMENT} ${POPSIZE} ${OFFSPRINGSIZE} --max-evals=${buckets}"
# NOTE: irace seems to capture both stderr and stdout, so you should not output to stderr
echo ${cmd} > ${STDERR}
$cmd 2> ${STDERR} | tee ${STDOUT}

# The following code is useless if the binary only output a single number on stdout.

# 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.
# It assumes that the objective value is the first number in
# the first column of the last line of the output.
# if [ -s "${STDOUT}" ]; then
#     COST=$(tail -n 1 ${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
