#!/bin/bash -e


case $1 in
    *.exp) ;;
    *) echo "bad file extension: $1"; exit 1;;
esac


GAMEDIR="games"

. $1


PETRUS_VERSION="$(grep 'version :=' ../build.sbt|cut -d\" -f 2)"

outdir=$(basename $1 .exp)

mkdir $outdir
mkdir $outdir/games $outdir/configs

for s in $GAMES; do
    cat ../$GAMEDIR/$s.set >> $outdir/games.list
    echo >> $outdir/games.list
done

for g in $(cat $outdir/games.list); do
    cp ../$GAMEDIR//$g $outdir/games/
done

for c in $MIXED_CONFIGS; do
    cp ../mixed-configs/$c.json $outdir/configs
done

cat <<EOF > $outdir/try_pack.sh
#!/bin/bash

if [ -f ../$outdir.tar.xz ] ; then
   exit 0
fi

for config in configs/*.json; do 
    for repeat in \$(seq $REPEATS); do
        for game in games/*; do
                GAME=\$(basename \$game)
                CONFIG=\$(basename \$config .json)
		outprefix=out/\$GAME.\$CONFIG.\$repeat
	    	if [ ! -f  \$outprefix.result ]; then exit 0; fi
	done	
    done
done

tar -C.. -cJf ../$outdir.tar.xz $outdir/out/

EOF

cat <<EOF > $outdir/run-se.sh
#!/bin/bash
set -e

GAME=\$1
CONFIG=\$2
REPEAT=\$3

outprefix=out/\$GAME.\$CONFIG.\$REPEAT

export LD_LIBRARY_PATH=$LIBRARY_PATH

if [ ! -f \${outprefix}.result ] ; then 
  ../petrus-${PETRUS_VERSION}/bin/petrus-se ${PROG_OPTIONS} -g games/\$GAME -m configs/\$CONFIG.json -o \${outprefix}.result 2> \${outprefix}.err > \${outprefix}.out
fi

touch pack.lock

flock -x pack.lock ./try_pack.sh

EOF

cat <<EOF > $outdir/schedule.sh
#!/bin/bash

mkdir -p out

for config in configs/*.json; do 
    for repeat in \$(seq $REPEATS); do
        for game in games/*; do
	    	tsp ./run-se.sh \$(basename \$game) \$(basename \$config .json) \$repeat
	done	
    done
done

EOF

chmod a+x $outdir/*.sh

tar cJf $outdir.tar.xz $outdir
rm -r $outdir
