#!/bin/bash
set -e

GAME=$1
MOVES=$2
TRANS=$3
MPSONLY=$4

MY_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
. $MY_DIR/paths.inc


if [ -z "$SOLVERCONF" ] ; then
    if [ -e ~/.config/petrus/solver.sh ] ; then
	. ~/.config/petrus/solver.sh
    else
	echo 'Gurobi configuration is required !'; exit 1;
    fi 
else
    . "$SOLVERCONF"
fi

if [ $TRANS == NONE ]; then
    TRANSOPT=""
    TRANSSUFFIX=""
else
    TRANSOPT="--game-transformer ${MIXED_STRATEGY_CONFIGS_PATH}/${TRANS}.json"
    TRANSSUFFIX="tr$TRANS"
fi

GTOPT_PATH=$PETRUS_BIN_PATH/petrus-gtopt


case $GAME in
     *.json) 
	 PROBPREFIX=$(basename $GAME .json)$TRANSSUFFIX-$MOVES
	 ;;
     *.sgmt)
	 PROBPREFIX=$(basename $GAME)$TRANSSUFFIX-$MOVES
	 ;;
     *.nfgame)
	 PROBPREFIX=$(basename $GAME)$TRANSSUFFIX-0
esac

if [ -e ${PROBPREFIX}.mps.gz ] ; then
   NODEL=1
else 
    $GTOPT_PATH --game-config $GAME --round-limit $MOVES $TRANSOPT --move-codes ${PROBPREFIX}.codes   --output-file ${PROBPREFIX}.mps.gz
fi

if [ \! -z $MPSONLY ] ; then
    exit 0
fi

$GUROBI_PATH > ${PROBPREFIX}.gurobi.stat  <<EOF
from gurobipy import *
setParam("Threads", 1)
$GUROBI_ADDITIONAL_SETTINGS
m = read("${PROBPREFIX}.mps.gz")
m.optimize()
m.write("${PROBPREFIX}.gurobi.sol.gz")
EOF

if [ \! -z "$NODEL" ]; then 
   rm ${PROBPREFIX}.mps.gz
fi
