#!/usr/bin/env bash
#
# Author: Makarius
#
# Poly/ML 5.1/5.2 startup script.
export -n INFILE OUTFILE MLTEXT TERMINATE NOWRITE
## diagnostics
function fail()
{
echo "$1" >&2
exit 2
}
function fail_out()
{
fail "Unable to create output heap file: \"$OUTFILE\""
}
function check_file()
{
[ ! -f "$1" ] && fail "Unable to locate \"$1\""
}
## compiler executables and libraries
[ -z "$ML_HOME" ] && fail "Missing ML installation (ML_HOME)"
POLY="$ML_HOME/poly"
check_file "$POLY"
if [ "$(basename "$ML_HOME")" = bin ]; then
POLYLIB="$(cd "$ML_HOME"; cd "$(pwd -P)"; cd ../lib; pwd)"
else
POLYLIB="$ML_HOME"
fi
export LD_LIBRARY_PATH="$POLYLIB:$LD_LIBRARY_PATH"
export DYLD_LIBRARY_PATH="$POLYLIB:$DYLD_LIBRARY_PATH"
## prepare databases
if [ -z "$INFILE" ]; then
INIT=""
EXIT="fun exit 0 = (OS.Process.exit OS.Process.success): unit | exit _ = OS.Process.exit OS.Process.failure;"
else
check_file "$INFILE"
INIT="(Signal.signal (2, Signal.SIG_HANDLE (fn _ => Process.interruptConsoleProcesses ())); PolyML.SaveState.loadState \"$INFILE\" handle Fail msg => (TextIO.output (TextIO.stdErr, msg ^ \": $INFILE\\n\"); OS.Process.exit OS.Process.failure));"
EXIT=""
fi
if [ -z "$OUTFILE" ]; then
COMMIT='fun commit () = false;'
MLEXIT=""
else
COMMIT="fun commit () = (PolyML.shareCommonData PolyML.rootFunction; TextIO.output (TextIO.stdOut, \"Exporting $OUTFILE\n\"); PolyML.SaveState.saveState \"$OUTFILE\"; true);"
[ -f "$OUTFILE" ] && { chmod +w "$OUTFILE" || fail_out; }
MLEXIT="commit();"
fi
## run it!
MLTEXT="$INIT $EXIT $COMMIT $MLTEXT"
if [ -z "$TERMINATE" ]; then
FEEDER_OPTS=""
else
FEEDER_OPTS="-q"
fi
"$ISABELLE_HOME/lib/scripts/feeder" -p -h "$MLTEXT" -t "$MLEXIT" $FEEDER_OPTS | \
{ read FPID; "$POLY" -q $ML_OPTIONS; RC="$?"; kill -HUP "$FPID"; exit "$RC"; }
RC="$?"
[ -n "$OUTFILE" -a -f "$OUTFILE" -a -n "$NOWRITE" ] && chmod -w "$OUTFILE"
exit "$RC"
#:wrap=soft:maxLineLen=100: