#!/usr/bin/env bash
#
# Author: Makarius
#
# DESCRIPTION: build Isabelle documentation
## diagnostics
PRG="$(basename "$0")"
function usage()
{
  echo
  echo "Usage: isabelle $PRG [OPTIONS] [SESSIONS ...]"
  echo
  echo "  Options are:"
  echo "    -a           select all doc sessions"
  echo "    -j INT       maximum number of parallel jobs (default 1)"
  echo "    -s           system build mode"
  echo
  echo "  Build Isabelle documentation from (doc) sessions."
  echo
  exit 1
}
function fail()
{
  echo "$1" >&2
  exit 2
}
function check_number()
{
  [ -n "$1" -a -z "$(echo "$1" | tr -d '[0-9]')" ] || fail "Bad number: \"$1\""
}
## process command line
declare -a BUILD_ARGS=()
# options
ALL_DOCS="false"
while getopts "aj:s" OPT
do
  case "$OPT" in
    a)
      ALL_DOCS="true"
      ;;
    j)
      check_number "$OPTARG"
      BUILD_ARGS["${#BUILD_ARGS[@]}"]="-j"
      BUILD_ARGS["${#BUILD_ARGS[@]}"]="$OPTARG"
      ;;
    s)
      BUILD_ARGS["${#BUILD_ARGS[@]}"]="-s"
      ;;
    \?)
      usage
      ;;
  esac
done
shift $(($OPTIND - 1))
# arguments
if [ "$ALL_DOCS" = true ]; then
  BUILD_ARGS["${#BUILD_ARGS[@]}"]="-g"
  BUILD_ARGS["${#BUILD_ARGS[@]}"]="doc"
else
  [ "$#" -eq 0 ] && usage
fi
BUILD_ARGS["${#BUILD_ARGS[@]}"]="--"
while [ "$#" -ne 0 ]; do
  BUILD_ARGS["${#BUILD_ARGS[@]}"]="$1"
  shift
done
## main
OUTPUT="$ISABELLE_TMP_PREFIX$$"
mkdir -p "$OUTPUT" || fail "Bad directory: \"$OUTPUT\""
"$ISABELLE_TOOL" build -R -b "${BUILD_ARGS[@]}"
RC=$?
if [ "$RC" = 0 ]; then
  "$ISABELLE_TOOL" build -o browser_info=false -o "document=pdf" \
    -o "document_output=$OUTPUT" -c "${BUILD_ARGS[@]}"
  RC=$?
fi
if [ "$RC" = 0 ]; then
  cp -f "$OUTPUT"/*.pdf "$ISABELLE_HOME/doc"
fi
rm -rf "$OUTPUT"
exit $RC