#!/bin/bash
###############################################################################
#
# PARAMETERS:
# $1 is the configuration number
# $2 is the instance id
# $3 is the seed
# $4 is the instance name
# The rest are parameters for running the program
#
# RETURN VALUE:
# This script should print nothing.
# Exit with 0 if no error, with 1 in case of error
###############################################################################
error() {
    echo "`TZ=UTC date`: $0: error: $@"
    exit 1
}

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

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

# TODO: Use /tmp for all temporary files, i.e., put target-runner-data under /tmp
tmp="./target-data"
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

