#!/bin/bash

# Path to spear:
EXE=~/bin/Spear-32_1.2.1

# What "fixed" parameters should be always passed to spear?
# The max time to be used is $TIMEOUT seconds:
TIMEOUT=300
FIXED_PARAMS="--nosplash --time --tmout $TIMEOUT"

# The instance name and the candidate id are the first parameters
CANDIDATE=$1
INSTANCE_ID=$2
SEED=$3
INSTANCE=$4

# All other parameters are the candidate parameters to be passed to spear
shift 4 || exit 1
CAND_PARAMS=$*

MYDIR=`mktemp -d`

STDOUT="${MYDIR}/c${CANDIDATE}-${INSTANCE_ID}.stdout"
STDERR="${MYDIR}/c${CANDIDATE}-${INSTANCE_ID}.stderr"

#echo "$EXE ${FIXED_PARAMS} --dimacs $INSTANCE --seed $SEED ${CAND_PARAMS}"

# Now we can call spear by building a command line with all parameters for it
$EXE ${FIXED_PARAMS} --dimacs $INSTANCE --seed $SEED ${CAND_PARAMS} 1> ${STDOUT} 2> ${STDERR}

# In case of error, we print the current time:
error() {
    echo "`TZ=UTC date`: error: $@" >&2
    exit 1
}

# Evaluate a floating point number subordinate expression.
function float_cond()
{
    local cond=0
    if [[ $# -gt 0 ]]; then
        cond=$(echo "$*" | bc -q 2>/dev/null)
        if [[ -z "$cond" ]]; then cond=0; fi
        if [[ "$cond" != 0  &&  "$cond" != 1 ]]; then cond=0; fi
    fi
    local stat=$((cond == 0))
    return $stat
}

if ERROR=$(cat ${STDERR} | grep 'Error:'); then
   echo "$TIMEOUT"
fi

# If the file exist, it contains the whole output written by spear.
# This script should return a single numerical value, the time used
# by this run of spear. The following line is to extract
# this value from the file containing spear output.
if COST=$(cat ${STDOUT} | grep -e '^c runtime [0-9]' | cut -f3 -d ' '); then
    if float_cond "$COST > $TIMEOUT"; then
        echo "$TIMEOUT"
    else
        echo "$COST"
    fi
    rm -Rf ${STDOUT} ${STDERR} ${MYDIR}
    exit 0
else
    error "${STDOUT}: No such file or directory"
fi

