#!/usr/bin/env bash
#
# $Id: run-mosml,v 1.8 2004/06/21 08:25:58 kleing Exp $
# Author: Markus Wenzel, TU Muenchen
#
# Moscow ML 2.00 startup script

export -n INFILE OUTFILE COPYDB COMPRESS MLTEXT TERMINATE NOWRITE


## diagnostics

function fail_out()
{
  echo "Unable to create output heap file: \"$OUTFILE\"" >&2
  exit 2
}


## prepare databases

MOSML="mosml -P sml90"

if [ -z "$INFILE" ]; then
  EXIT='load "OS"; fun exit 0 = (OS.Process.exit OS.Process.success): unit | exit _ = OS.Process.exit OS.Process.failure;'
else
  EXIT=""
  echo "Cannot load images yet!" >&2
  exit 2
fi

if [ -z "$OUTFILE" ]; then
  COMMIT='fun commit () = (TextIO.output (TextIO.stdErr, "Error - Database is not opened for writing.\n"); false);'
else
  COMMIT="fun commit () = true;"
  echo "WARNING: cannot save images yet!" >&2
  [ -f "$OUTFILE" ] && { chmod +w "$OUTFILE" || fail_out; }
fi


## run it!

MLTEXT="$EXIT $COMMIT $MLTEXT"
MLEXIT="commit();"

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; "$ML_HOME"/$MOSML $ML_OPTIONS 2>&1; RC="$?"; kill -HUP "$FPID"; exit "$RC"; }
RC="$?"

[ -n "$OUTFILE" -a -f "$OUTFILE" -a -n "$NOWRITE" ] && chmod -w "$OUTFILE"

exit "$RC"
