#!/bin/bash
# first 
# export STAREXEC_WALLCLOCK_LIMIT=300
# comment
#set -x

#export TPTP=$(./get_tptp_variable.sh $1)
export HERE=$(dirname $0)

FILE_SMT=$1

# Increase the soft ulimit
ulimit -s 200000

TFF_TMP=$(mktemp $HERE/iprover.tff.XXXXXX)
TCF_TMP=$(mktemp $HERE/iprover.tcf.XXXXXX)


#-----------kill children

function killtree {
    local ppid=$1
    if [ "$SYS" = "Darwin" ]; 
    then
        local CHILDREN=`ps -o pid,ppid | awk -v ppid=$ppid '$2 ~ ppid' | awk '{print $1;}'`
#       local CHILDREN=`pstree -p $ppid | tr "\n" " " |sed "s/[^0-9]/ /g" |sed "s/\s\s*/ /g"`
        #local CHILDREN=`ps -o pid,ppid | grep '^[0-9]' | grep ' '$ppid | cut -f 1 -d ' '`
    else
        local CHILDREN=`ps -o pid --no-heading --ppid $ppid`
    fi
     

    if [ ! -z "$CHILDREN" ];
    then
        for child_pid in ${CHILDREN}; 
        do
            killtree ${child_pid}
        done
    fi
   # kill -TERM ${ppid}
    kill -9 ${child_pid} 2>/dev/null
}

function killChildProcesses {

    killtree "$$"
}

function terminate {
        killChildProcesses
#     rm -r "$TMP"
     echo "Time Out Real"
     wait

     exit $1
}

function interrupted {
#       echo "interrupted" >> $LOGFILE
        echo "Terminated"
        terminate 0
}

trap interrupted SIGINT SIGQUIT SIGTERM

#------------ end kill children

# SMT to TFF

nohup  java -jar $HERE/res/smttotptp-0.9.9.jar $FILE_SMT $TFF_TMP &>/dev/null &
PID=$!
wait $PID

smttotptp_exit_status=$?

if [ $smttotptp_exit_status -ne 0 ]; then
# directly clausify  SMT with Vampire 
    nohup $HERE/res/vclausify_rel --input_syntax smtlib2 --mode tclausify $FILE_SMT > $TCF_TMP 2>/dev/null &
else	
    # clausify TFF_TMP
    $HERE/res/vclausify_rel --mode tclausify $TFF_TMP > $TCF_TMP 2>/dev/null &
fi	

PID=$!  
wait $PID
vclausify_exit_status=$?


if [ $vclausify_exit_status -ne 0 ]; then
    echo unknown	
else
# run iProver
    out=$(python3 prover_driver.py --schedule_mode external --schedule smt_4000_super_300_4 --no_cores 4 $TCF_TMP $STAREXEC_WALLCLOCK_LIMIT 2>/dev/null)
    if echo $out | grep -q "SZS status Theorem\|SZS status Unsatisfiable"
    then
	echo "unsat"
    else	
	if echo $out | grep -q "SZS status CounterSatisfiable\|SZS status Satisfiable"
	then
	    echo "sat"
	else
	    echo "unknown"
	fi	
    fi
fi

rm $TFF_TMP
rm $TCF_TMP

