#!/bin/ksh93

CMD=${.sh.file##*/}
if [[ -z ${SMLNJ_HOME} ]] ; then
	BIN_DIR="@CLIENT_BASEDIR@/lib/smlnj/bin"
	LIB_DIR="@CLIENT_BASEDIR@/lib/smlnj/lib"
else
	BIN_DIR=${SMLNJ_HOME}/bin
	LIB_DIR=${SMLNJ_HOME}/lib
fi

[[ -z ${CM_PATHCONFIG} ]] && export CM_PATHCONFIG="${LIB_DIR}/pathconfig"

SML="${BIN_DIR}/sml"
LINK="${BIN_DIR}/.link-sml"

function cleanup {
	[[ -n ${TDIR} && -d ${TDIR} ]] && rm -rf "${TDIR}"
	return 0
}

TDIR=${ mktemp -d /tmp/sml.XXXXXX ; }
[[ -z ${TDIR} ]] && exit 2

smlfile=${TDIR}/export.sml
cmfile=${TDIR}/export.cm
listfile=${TDIR}/BOOTLIST
linkargsfile=${TDIR}/LINKARGS

dulist=

trap cleanup EXIT

function usage {
	print -u2 "${CMD}: $@"
	print -u2 "Usage: ${CMD} [-S setup] root-group [main-function [heapfile]]"
	exit 1
}

setup=

while (( $# )); do
	case $1 in
		-D*|-U*|-C*) dulist+=" $1" ; shift ;;
		-S) (( $# == 1 )) && usage "missing argument for -S"
			setup="$1" ; shift 2 ;;
		*) break ;;
	esac
done

if (( $# == 4 )) ; then
    setup="$1"
    root="$2"
    main="$3"
    heap="$4"
elif (( $# == 3 )); then
    root="$1"
    main="$2"
    heap="$3"
elif (( $# == 2 )); then
    root="$1"
    main="$2"
    heap="${root##*/}"
    heap="${heap%.cm}"
elif (( $# == 1 )); then
    root="$1"
    # quick hack for now:
    main=Test.main
    heap="${root##*/}"
    heap="${heap%.cm}"
else
    usage "no CM description file specified"
fi

rare=XYZ_XXX_0123

cat >${smlfile} <<EOF
structure ${rare} = struct val _ = SMLofNJ.exportFn ("${heap}", ${main}) end
EOF

cat >${cmfile} <<EOF
Group structure ${rare} is \$/basis.cm ${PWD}/${root} ${smlfile}
EOF

# Invoke sml with special option that causes CM to do its magic.
# Unless the heap image exists and is up-to-date CM will write the arguments
# for the link script into $linkargsfile.
# (See src/cm/main/cm-boot.sml [function "mlbuild"] for details.)
"${SML}" ${dulist} @CMbuild ${setup} "${root}" "${cmfile}" "${heap}" \
	"${listfile}" "${linkargsfile}" || exit $?
[[ -r ${linkargsfile} ]] && "${LINK}" $(<${linkargsfile})
