#!/bin/bash

set -e
pvdir=$PWD

if [ ! -x ./analyze ]
then
    echo ERROR analyze not found
    exit 2
fi

if [ -d /local/bblanche/tmp ]
then
    TMPPARENT=/local/bblanche/tmp
else
    TMPPARENT=.
fi

TMPDIR="$(mktemp -d "$TMPPARENT/tmp.XXXXXXXXXX")"
TMP=$TMPDIR/tmp

# usage message, in case of bad arguments

function usage()
{
    cat <<'EOF'
Usage: test <mode> <test_set>
where <mode> can be:
- test: test the mentioned scripts
- test_add: test the mentioned scripts and add the
expected result in the script when it is missing
- add: add the expected result in the script when it is missing,
do not test scripts that already have an expected result
- update: test the mentioned scripts and update the expected
result in the script
and <test_set> can be: typed, untyped, or
dir <prefix> <list_of_directories>
- typed runs ProVerif on examples for the typed front-ends
- untyped runs ProVerif on examples for the untyped front-ends
- arinc runs ProVerif on the ARINC823 protocol
- dir <prefix> <list_of_directories> analyzes the mentioned directories
using ProVerif, using <prefix> as prefix for the output files.
EOF
    exit 2
}

# analyzedirlist <prefix> <list of directories>
# analyzes the ProVerif scripts in the given list of directories,
# and outputs the results in tests/<prefix>`date`
# with summary in tests/sum-<prefix>`date`
# and comparison with expected results on the standard output and in tests/res-<prefix>`date`

function analyzedirlist()
{
    prefix=$1
    shift
    for dir in "$@"
    do
	if [ -d "$dir" ]
	then
	    if [ -x "$dir/prepare" ]
	    then
		cd "$dir"
		./prepare
		cd "$pvdir"
	    fi
	fi
    done
    ./analyze PV "$mode" "$TMPDIR" "$prefix" dirs "$@"
}

mkdir -p tests

case X$1 in
    X)  mode=test;;
    Xtest|Xtest_add|Xadd|Xupdate)
	mode=$1
	shift;;
    *)  echo "Error: unknown mode $1."
	usage;;
esac

case X$1 in
    X|Xtyped)
	analyzedirlist typed examples/pitype/secr-auth examples/pitype/noninterf examples/pitype/weaksecr examples/pitype/choice examples/pitype/lemma examples/cryptoverif examples/pitype/jfk examples/pitype/certified-mail-AbadiGlewHornePinkas/onefile examples/pitype/certified-mail-AbadiGlewHornePinkas/journalsas examples/pitype/ffgg examplesnd/lemmas examplesnd/pitype examplesnd/fromcv examplesnd/Ukano unclearIP/examples/pitype/sync ;;
    Xuntyped)
	analyzedirlist untyped examples/horn/secr examples/pi/secr-auth examples/pi/noninterf examples/pi/weaksecr examples/pi/choice examples/pi/jfk examples/pi/mailprotAbadi/onefile2 examples/pi/mailprotAbadi/journalsas2 examples/pi/ffgg examplesnd/attackspeed examplesnd/pibugs examplesnd/bugs unclearIP/examples/pi/sync ;;
    Xarinc)
	analyzedirlist arinc examples/pitype/arinc823 ;;
    Xdir)
	# test dir <prefix> <list of directories>
	# analyzes the CryptoVerif scripts in the given list of directories,
	# and outputs the results in tests/<prefix>`date`
	shift
	analyzedirlist "$@";;
    *)  echo "Unknown analysis set $1"
	usage
esac

rm -r "$TMPDIR"
