#!/bin/bash

set -e 

GAME=$1
CF=$2
GTOPTCONF=$3

RAGG=/home/jan/research/security_games/petrus/aggregate_gtopt.R
SOLVER_DIR=/home/jan/research/security_games/gtres11


JOINT_RESULTS_FILE=$GAME-$CF-$GTOPTCONF.join.csv
STAT_FILE=$GAME-$CF-$GTOPTCONF.stat.csv

RAND_RESULT=../../exact/eval-$GAME-$CF-random.1.out
GTOPT_RESULT=../../exact/eval-$GAME-$CF-milp.1.out
SCIP_RESULT=../../exacteval-$GAME-$CF--milp3.1.out


TEMPFILE=$(tempfile)

echo uctAttackerPayoff,uctDefenderPayoff,uctTimeMs,gtoptAttackerPayoff,gtoptDefenderPayoff,gtoptTime,gurobiTime,randomAttackerPayoff,randomDefenderPayoff,scipAttackerPayoff,scipDefenderPayoff > $JOINT_RESULTS_FILE

for resfile in eval-$GAME-$CF-$GTOPTCONF.*.out; do
    if [ -f $resfile ] ; then 
	grep "The payoff: " $resfile |cut -f 2 -d : | head -n 2 > $TEMPFILE
	grep "Time: " $resfile | cut -f 2 -d : >> $TEMPFILE
    else
	echo NA >> $TEMPFILE
	echo NA >> $TEMPFILE
	echo NA >> $TEMPFILE
    fi
    grep "The payoff: " $GTOPT_RESULT | cut -f 2 -d : >> $TEMPFILE
    if [ -f $SOLVER_DIR/$GAME-$CF.stat ] ; then 
	grep "Total Time " $SOLVER_DIR/$GAME-$CF.stat | cut -f 2 -d : >> $TEMPFILE
    else
	echo NA >> $TEMPFILE
    fi
    if [ -f $SOLVER_DIR/$GAME-$CF.gurobi.stat ]; then
	grep Explored  $SOLVER_DIR/$GAME-$CF.gurobi.stat | grep -o -E '[0-9]*(\.[0-9]*) seconds'| cut -d\  -f 1 >> $TEMPFILE
    else
	echo NA >> $TEMPFILE
    fi
    grep "The payoff: " $RAND_RESULT | cut -f 2 -d : >> $TEMPFILE

    if [ -f $SCIP_RESULT ] ; then 
	grep "The payoff: " $SCIP_RESULT | cut -f 2 -d : >> $TEMPFILE
    else
	echo NA >> $TEMPFILE
    fi
    
    
    paste -d, -s < $TEMPFILE >> $JOINT_RESULTS_FILE
    Rscript $RAGG $JOINT_RESULTS_FILE $STAT_FILE $GAME $GTOPTCONF 
done
