#!/usr/bin/env bash
#
# Author: Gerwin Klein, NICTA
#
# Tests all entries in Archive of Formal Proofs
# 

## settings

function usage()
{
  echo
  echo "Usage: $PRG OPTIONS [entries]"
  echo
  echo "  Runs isabelle build on specified entries in the Archive of Formal Proofs"
  echo 
  echo "Options:"
  echo "-t <path/to/isabelle>  use isabelle tool wrapper at specified path"     
  echo "-c                     include target clean (rebuild session)"
  echo "-r                     use env variable ISABELLE_RELEASES to find isabelle"
  echo 
  echo "Examples:"
  echo
  echo "$PRG"
  echo   "uses isabelle in your normal path to run all tests (usually = devel version)"
  echo
  echo "$PRG Example-Submission"
  echo   "same as above, but only test Example-Submission"
  echo
  echo "$PRG -t /usr/proj/isabelle/Isabelle2009/bin/isabelle Example-Submission"
  echo   "uses the Isabelle2009 release version to run the test"
  echo
  echo "$PRG -r Isabelle2009 Example-Submission"
  echo   "uses the distribution $ISABELLE_RELEASES/Isabelle2009 to test Example-Submission"
  exit 1
}

function fail()
{
  echo "$1" >&2
  exit 2
}

function timestamp()
{
   echo "[timestamp: `date "+%Y-%m-%d %H:%M:%S"`]"
}

function check_isabelle()
{
  [ -x $ISABELLE_TOOL ] || fail "No isabelle tool wrapper found at [$ISABELLE_TOOL]."
  ML_IDENTIFIER=`$ISABELLE_TOOL getenv -b ML_IDENTIFIER` || fail "could not identify ML system"
  ISABELLE_HOME=`$ISABELLE_TOOL getenv -b ISABELLE_HOME` || fail "could not find Isabelle home"
  [ -n "$ISABELLE_IMAGE_PATH" ] || export ISABELLE_IMAGE_PATH="$ISABELLE_HOME/heaps/$ML_IDENTIFIER/"
}

## 

PRG="$(basename "$0")"
THYS="$(dirname "$0")/../thys"

[ "$1" = "-?" ] && usage

[ "$ISABELLE_RELEASES" == "" ] && fail "ISABELLE_RELEASES not set"
# for dev version:
# ISABELLE_TOOL=isabelle
# for release version:
ISABELLE_TOOL="$ISABELLE_RELEASES/Isabelle2016/bin/isabelle"
check_isabelle

INCLUDE_INFREQUENT="yes"
INCLUDE_FREQUENT="yes"


while getopts "t:cr:" OPT
do
    case "$OPT" in
      r)
        [ "$ISABELLE_RELEASES" == "" ] && fail "ISABELLE_RELEASES not set"
        ISABELLE_TOOL="$ISABELLE_RELEASES/$OPTARG/bin/isabelle"
        check_isabelle
        ;;
      c)
        CLEAN="-c"
        ;;
      t)
        ISABELLE_TOOL="$OPTARG"
        check_isabelle
        ;;
    esac
done

shift $(($OPTIND - 1))

[ -d $THYS ] || fail "Could not find archive directory. Tried [$THYS]."
cd $THYS

DIRS=""
OPTS=""
for ARG in "$@"
do
  if [ "${ARG#*=}" == "$ARG" ]
  then
    DIRS="$DIRS $ARG"
  else
    OPTS="$OPTS $ARG"
  fi
done
if [ "$DIRS" == "" ]; then DIRS="-g AFP"; fi

timestamp

$ISABELLE_TOOL build -o browser_info -o "document=pdf" -o "document_variants=document:outline=/proof,/ML" -v -d . $CLEAN $DIRS

timestamp
