#!/bin/sh
#
# COPYRIGHT (c) 2020 The Fellowship of SML/NJ (http://www.smlnj.org)
# All rights reserved.
#
# script to compile using the batch compiler
# usage:
#	cmb-make [ <sml-cmd> ] <flags> ...
#
# Do a batch compiler of the compiler; the optional <sml-cmd> argument specifes
# the path to the SML compiler to use for the build.
#

HERE=`pwd`

usage() {
  echo "usage: cmb-make [ options ] [ <sml-cmd> ]"
  echo "  options:"
  echo "    -h            -- print this message"
  echo "    -verbose      -- set CM's verbose mode to true"
  echo "    -stats        -- report compiler statistics"
  echo "    -C<ctl>=<v>   -- control argument passed to compile command"
  echo "    -D<sym>=<v>   -- CM-define argument passed to compile command"
  exit 1
}

export CM_VERBOSE
CM_VERBOSE=false

SML=sml
ARGS=""
STATS="false"
# Process command-line arguments
#
while [ "$#" != "0" ] ; do
  arg=$1; shift
  case $arg in
    -h) usage ;;
    -verbose) CM_VERBOSE=true ;;
    -stats) STATS=true ;;
    -32)
	echo "cmb-make: 32-bits not supported anymore"
	usage
	;;
    -64) ;;
    -C*) ARGS="$ARGS $arg" ;;
    -D*) ARGS="$ARGS $arg" ;;
    *)  SML=$arg
	break
	;;
  esac
done

# if the "sml" command is specified by a path, then we add the directory
# containing the "sml" command to the end of the user's PATH.  This allows
# CM to find the ml-yacc and ml-ulex programs when they are not in the path.
# NOTE: the "-DNO_PLUGINS" option used below should obviate the need for these
# commands, but the way that the CM parser handles #ifdef is broken.
#
SMLBIN=`dirname $SML`
case $SMLBIN in
  .) ;;
  /*) ;;
  *) if [ -d $SMLBIN ] ; then
      SMLBIN=$(cd $SMLBIN; pwd)
    else
      echo "cmb-make: directory '$SMLBIN' does not exist"
      exit 1
    fi ;;
esac
if [ $SMLBIN != "." ] ; then
  if [ x"$CM_VERBOSE" = xtrue ] ; then
    echo "cmb-make: adding '$SMLBIN' to PATH"
  fi
  PATH=$PATH:$SMLBIN
fi

exec $SML $ARGS $@ -DNO_PLUGINS '$smlnj/cmb.cm' <<XXXX
(if $STATS then Stats.reset() else ();
CMB.make();
if $STATS then Stats.summary() else ());
XXXX
