#!/usr/bin/env bash
#
# Author: Markus Wenzel, TU Muenchen
#
# SML/NJ startup script (for 110 or later).

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_mlhome_file()
{
  [ ! -f "$1" ] && fail "Unable to locate \"$1\""
}

function check_heap_file()
{
  if [ ! -f "$1" ]; then
    echo "Expected to find ML heap file $1" >&2
    return 1
  else
    return 0
  fi
}



## compiler binaries

[ -z "$ML_HOME" ] && fail "Missing ML installation (ML_HOME)"

SML="$ML_HOME/sml"
ARCH_N_OPSYS="$ML_HOME/.arch-n-opsys"

check_mlhome_file "$SML"
check_mlhome_file "$ARCH_N_OPSYS"

eval $("$ARCH_N_OPSYS")



## prepare databases

if [ -z "$INFILE" ]; then
  EXIT="fun exit rc = Posix.Process.exit (Word8.fromInt rc);"
  DB=""
else
  EXIT=""
  DB="@SMLload=$INFILE"
fi

if [ -z "$OUTFILE" ]; then
  COMMIT='fun commit () = false;'
  MLEXIT=""
else
  if [ -z "$INFILE" ]; then
    COMMIT="fun commit () = if SMLofNJ.exportML \"$OUTFILE\" then () else OS.FileSys.rename {old = \"$OUTFILE.$ARCH-$OPSYS\", new = \"$OUTFILE\"};"
  else
    COMMIT="fun commit () = (ML_System.share_common_data (); ML_System.save_state \"$OUTFILE\");"
  fi
  [ -f "$OUTFILE" ] && { chmod +w "$OUTFILE" || fail_out; }
  MLEXIT="commit();"
fi


## run it!

MLTEXT="$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; "$SML" $ML_OPTIONS "$DB"; RC="$?"; kill -TERM "$FPID"; exit "$RC"; }
RC="$?"


## fix heap file name and permissions

if [ -n "$OUTFILE" ]; then
  check_heap_file "$OUTFILE" && [ -n "$NOWRITE" ] && chmod -w "$OUTFILE"
fi

exit "$RC"
