#!/bin/bash

DGARGS="--no-logging"
PREFIX="."
DISPLAYTIME=0
BSDTIME=0
VERBOSE=0
TMPFILE=$(mktemp)
USAGE="\nUsage: $0 [-t][-v][-h] examplename\nOptions:\n  -t\tShow execution time\n  -T\tShow execution time (BSD time)  -V\tVerbose\n  -h\tThis help message"

set -e # stop on error, echo command

# Run command and record time (if turned on)
recordtime() {
    if [ "$DISPLAYTIME" != "0" ]; then
        /usr/bin/time -f "  $1 %e" -a -o $TMPFILE $*
    elif [ "$BSDTIME" != "0" ]; then
        time $*
    else
        $*
    fi
}

while getopts ":t:h:T:V" opt; do
    case $opt in
    t)  # Display timing info
        DISPLAYTIME=1
        shift
        ;;
    h)  # Help
        echo "$USAGE" && exit 0 # Help message
        ;;
    T)  # Display time info (BSD time)
        BSDTIME=1
        shift
        ;;
    V)  # Verbose mode
        VERBOSE=1
        shift
        ;;
    \?) # unrecognised argument
        echo "Error: Option $OPTARG not allowed\n$USAGE" && exit 0
        ;;
    esac
done

# Argument (example name) check.
[ $# -ge 1 ] || (echo "Error: Not enough arguments\n$USAGE" && exit 1)

# Is example valid?
[ -f "$PREFIX/$1/main.go" ] || (echo "Error: $PREFIX/$1/main.go does not exist" && exit 1)

mkdir -p out
echo "----- $1 -----"
[ "$VERBOSE" != "1" ] || set -x # Verbose mode

PATH="$PATH:." recordtime dingo-hunter infer "$PREFIX/$1/main.go" \
    --output "out/$1.migo" $DGARGS
PATH="$PATH:." recordtime Gong -A "out/$1.migo"

[ "$VERBOSE" != "1" ] || set +x # Verbose mode

if [ "$DISPLAYTIME" != "0" ]; then
    echo "Timing results in seconds:"
    cat $TMPFILE
fi
rm $TMPFILE
