#!/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
}

CONFIG_ID=$1
INSTANCE_ID=$2
SEED=$3
INSTANCE=$4


EXE=/Benchmark/bin/RunTest
FIXED_PARAMS=" -I $INSTANCE -O OUT/ -D ALGO TIME_MAX  120 "

shift 4 || error "Not enough parameters"
CONFIG_PARAMS=$*

STDOUT=c${CONFIG_ID}-${INSTANCE_ID}-${SEED}.stdout
STDERR=c${CONFIG_ID}-${INSTANCE_ID}-${SEED}.stderr

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


start=`date +%s`

$EXE ${FIXED_PARAMS} ${CONFIG_PARAMS} > ${STDOUT} #/dev/null 2>&1


#$EXE ${FIXED_PARAMS} -I $INSTANCE/old_input.csv -O ~/MIRA-OUT/ --seed ${SEED}  ${CONFIG_PARAMS} 1> ${STDOUT} 2> ${STDERR} /dev/null 2>&1


# This is for printing the final objective value function a number from the output.
if [ -s "${STDOUT}" ]; then
#    grep "Objective:" ${STDOUT} | sort $2| tail -n 1| awk '{print -$2}'
    cost=$(grep "Objective:" ${STDOUT} | sort -k2 -n| tail -n 1| awk '{printf -$2}')
    end=`date +%s`
    runtime=$((end-start))
    echo $cost $runtime
    rm -f "${STDOUT}" "${STDERR}"
    exit 0
else
    error "${STDOUT}: No such file or directory"
fi
