#!/bin/bash
###############################################################################
#
# PARAMETERS:
# $1 is the 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 a single numerical value (the value to be minimized)
###############################################################################
# If you want to find where target-runner is.
#BINDIR=$(dirname "$(readlink -f "$(type -P $0 || echo $0)")")
EXE=~/bin/moaco_btsp

CONFIGURATION=$1
INSTANCEID=$2
SEED=$3
INSTANCE=$4
shift 4 || error "Not enough parameters to $0"

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

# TODO: Use /tmp for all temporary files, i.e., put target-runner-data under /tmp
tmp="./target-runner-tmp"
mkdir -p ${tmp}
cd ${tmp} || error "cannot change to directory \'${tmp}\'"

# Here we transform some parameters.
PARAMS=
while [ $# -gt 0 ]; do
    case "$1" in
        --ants) shift; ANTS="$1"; shift;;
        --Mants) shift; MANTS="$1"; let "ANTS = (3 * 2 * $MANTS)"; shift;;
        *) PARAMS="$PARAMS $1"; shift;;# terminate case
    esac
done

ISIZE=$(basename $INSTANCE | cut -f1 -d'-')
let "RUNTIME = (4 * (($ISIZE / 100) ** 2))"

FIXED_PARAMS="--trials 1 --wls 1 --aco mmas --time $RUNTIME --ants $ANTS --input $INSTANCE --seed $SEED"

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

exec 2> $STDERR
$EXE ${FIXED_PARAMS} ${PARAMS} 1> $STDOUT
RET=$?
echo "OK" >& 2
exit $RET

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