#!/bin/sh

copy=0
dirset=0
dir=""
pvs=pvs
# currently the longest running proof is physical_read_ok with 21 secs
# but typechecking takes 2:20...
timeout=180
useold=0
uselog=0
starttime=$(date +%s)

if [ -f Validate/validate -a -f everything.pvs ] ; then
    true
else
    echo start this script from the model directory as Validate/validate
    exit 1
fi

usage(){
    echo usage: Validate/validate [-h] [-timeout secs] [-pvs pvsprog] [-c] [dir]
    echo "  -h            displays this message"
    echo "  -timeout secs sets the timeout in seconds [default 240]"
    echo "  -old          discard timed-status and use backup copy timed-status-old"
    echo "  -pvs          selects the pvs to run"
    echo "  -c            copies the current dir to /tmp and runs the validation there"
    echo "  -log          do not run PVS, reuse old log file"
    echo "  specifying a dir implies -c and copies to the specified dir"
    exit 1
}

while [ $# -gt 0 ] ; do
    case $1 in
	-h|--help)
	    usage;;
	-c)
	    copy=1; shift;;
	-timeout)
	    if [ $# -lt 2 ] ; then
		usage
	    fi
	    timeout=$2; shift; shift;;
	-old)
	    useold=1; shift;;
	-pvs)
	    if [ $# -lt 2 ] ; then
		usage
	    fi
	    pvs=$2; shift; shift;;
	-log)
	    uselog=1; shift;;
	-*)
	    usage;;
	*)
	    copy=1; dirset=1; dir=$1; shift;;
    esac
done

if [ $copy == 1 ] ; then
    # set -x
    if [ $dirset == 0 ] ; then
	if [ $USER == "tews" ] ; then
	    dir=/tmp/tews/validate
	else
	    dir=/tmp/validate
	fi
    fi

    rm -rf $dir
    cp -a . $dir
    cd $dir
    Validate/validate -pvs $pvs
    exit $?
fi


if [ $uselog = 0 ] ; then
    date +'%nstarting on %a %d %b %Y %H:%M:%S %Z (%z)%n' > Validate/log
fi

# backup copy for timed-status
if [ $useold = 0 ] ; then
    mv Validate/timed-status Validate/timed-status-old
else
    rm Validate/timed-status
fi

if [ $uselog = 0 ] ; then
    $pvs -batch -v 2 -load Validate/batch.el -timeout $timeout \
	| tee -a Validate/log \
	| Validate/filter.perl
else
    cat Validate/log \
	| Validate/filter.perl
fi

if [ $uselog = 0 ] ; then
    date +'%nfinished on %a %d %b %Y %H:%M:%S %Z (%z)%n' >> Validate/log
fi

Validate/make-status-diff | tee Validate/status-diff

sed -e '/./ s/([ .0-9]* s)/( ? s)/g' \
    -e '/./ s/- complete  //' \
    -e '/./ s/- incomplete//' \
    -e '/./ s/\.*proved /...proved /' \
    -e '/./ s/\.*unfinished /...unfinished /' \
    -e '/./ s/\.*untried /...untried /' \
    -e '/./ s/ *\[shostak\]/  [SHOSTAK]/' \
    -e '/./ s/ *\[SHOSTAK\]/  [SHOSTAK]/' \
    -e '/./ s/ *\[Untried\]/  [Untried]/' \
    < Validate/timed-status > Validate/status

seconds=$(( $(date +%s) - $starttime))
hour=$(($seconds / 3600))
seconds=$(( $seconds - $hour * 3600))
minute=$(($seconds / 60))
seconds=$(( $seconds - $minute * 60))

printf "running time %d:%02d:%02d\n" $hour $minute $seconds
