#!/bin/bash

# Wrapper script for LP2ACYC + ACYC2MIP + CPLEX (optimizing)

if test $# -ne 3
then
  echo "The script $0 must be invoked with three parameters!"
  exit 128
fi

trap ":" 24 15

BIN=`dirname $0`
TMP=${BIN%%/bin}/tmp

unid=`hostname -s`-$$
symfile=$TMP/$unid-symbols.sm
infile=$TMP/$unid-input.lp
outfile=$TMP/$unid-output.txt

gringo-aspcomp2014 --foobar="$3" 2>/dev/null \
| $BIN/lpstrip-1.8 2>/dev/null \
| $BIN/lpcat-1.25 -s=$symfile 2>/dev/null \
| $BIN/lpshift-1.2 2>/dev/null \
| $BIN/lp2normal2-1.7 -ko 2>/dev/null \
| $BIN/lp2acyc-1.12 2>/dev/null \
| $BIN/acyc2solver-1.5 --mip 2>/dev/null >$infile

declare -a rvals=("${PIPESTATUS[@]}")

if test ${rvals[0]} -ne 0
then
  echo "Grounding error!"
  rm -f $symfile $infile
  exit 128
fi

for i in 1 2 3 4 5
do
  if test ${rvals[$i]} -ne 0
  then
    echo "UNKNOWN"
    rm -f $symfile $infile
    exit 1
  fi
done

if test "`head -2 $infile | tail -1`" = ""
then
  let opt=0
else
  let opt=1
fi

wd=`pwd`
cd $TMP
( echo "read "$infile; \
  echo "set threads 1"; \
  echo "optimize"; \
  echo "display solution variables var_*" ) \
| cplex > $outfile 2>/dev/null
rval=$?
cd $wd
rm -f $infile
rm -f $TMP/cplex.log
rm -f $TMP/clone*.log

if test $rval -ne 0
then
  echo "UNKNOWN"
  exit 1
fi

$BIN/judge $symfile $outfile $opt
rval=$?

exit $rval
