#!/usr/bin/env bash
#
# DESCRIPTION: process files generated by Why3


## diagnostics

PRG="$(basename "$0")"

function usage()
{
  echo
  echo "Usage: isabelle $PRG [OPTIONS] WHY3_FILE"
  echo
  echo "  Options are:"
  echo "    -b           batch mode"
  echo "    -i           interactive mode"
  echo
  echo "Process files generated by Why3."
  exit 1
}

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


## utilities

function make_theory()
{
  BNAME=`basename "$1"`

  if [ ! -e "$1.thy" ]; then
    echo -e "theory $BNAME\nimports Why3.Why3\nbegin\n\nwhy3_open \"$BNAME.xml\"\n" > "$1.thy"
    sed \
      -e 's/<lemma name="\([^"]*\)"[^>]*>/why3_vc \1\n\n/g' \
      -e 's/<[^l][^>]*>//g' \
      "$1.xml" >> "$1.thy"
    echo -e "why3_end\n\nend" >> "$1.thy"
  fi
}


## process command line

while getopts "bi" OPT
do
  case "$OPT" in
    b)
      BATCH=true
      ;;
    i)
      INTERACTIVE=true
      ;;
    \?)
      usage
      ;;
  esac
done


## main

shift $(($OPTIND - 1))

[ "$#" != 1 ] && usage

NAME=`dirname "$1"`/`basename "$1" .xml`

if [ "$ISABELLE_WHY3_SESSION" ]; then
  SESSION="$ISABELLE_WHY3_SESSION"
else
  SESSION=Why3
fi

if [ "$ISABELLE_WHY3_SESSION_DIR" ]; then
  SESSION_DIR=("-d" "$ISABELLE_WHY3_SESSION_DIR")
else
  SESSION_DIR=()
fi

if [ "$BATCH" = true ]; then
  if [ "$ISABELLE_ADDRESS" ]; then
    isabelle_client -t "$NAME"
  else
    "$ISABELLE_TOOL" process "${SESSION_DIR[@]}" -l "$SESSION" -T "$NAME"
  fi
elif [ "$INTERACTIVE" = true ]; then
  make_theory "$NAME"
  if [ -f "$JEDIT_SETTINGS/$WHY3_JEDIT_SERVER" ]; then
    "$ISABELLE_TOOL" java -jar "$(platform_path "$JEDIT_HOME/dist/jedit.jar")" \
      "-settings=$(platform_path "$JEDIT_SETTINGS")" "-server=$WHY3_JEDIT_SERVER" \
      -reuseview -wait "$(platform_path "${NAME}.thy")"
  else
    "$ISABELLE_TOOL" jedit "${SESSION_DIR[@]}" -l "$SESSION" "${NAME}.thy"
  fi
else
  usage
fi
