#!/usr/bin/env bash

set -e

# This script adds a new crosscompiler target for MLton.
#
# It takes four arguments.
#
# 1. <crossTarget>, which is waht MLton will pass via the -b flag to the GCC
#    cross-compiler tools.  You don't need to have installed these tools in order
#    to run this script, since it uses ssh and the native gcc on the target.
#    Examples of $crossTarget are i386-pc-cygwin and sparc-sun-solaris.
#
# 2. <crossArch> specifies the target architecture.  
#    The posibilities are: sparc, x86.
#
# 3. <crossOS> specifies the target OS.
#    The possibilities are: cygwin, solaris.
#
# 4. <machine> specifies a remote machine of the target type.  This script
#    will ssh to $machine to compile the runtime and to compile and run the
#    program that will print the values of all the constants that the MLton 
#    basis library needs.
#
# Here are some example uses of this script.
#
#   add-cross i386-pc-cygwin x86 cygwin cygwin
#   add-cross sparc-sun-solaris sparc solaris blade
#
# (Here cygwin happens to be the name of my Cygwin machine and blade
#  happens to be the name of my Sparc machine.)
#
# You also may need to set $libDir, which determines where the
# cross-compiler target will be installed.

die () {
	echo >&2 "$1"
	exit 1
}

usage () {
	die "usage: $name <crossTarget> <crossArch> <crossOS> <machine>"
}

case "$#" in
4)
	crossTarget="$1"
	crossArch="$2"
	crossOS="$3"
	machine="$4"
	;;
*)
	usage
	;;
esac

name=`basename $0`
original=`pwd`
dir=`dirname $0`
src=`cd $dir/.. && pwd`

# libDir is the mlton lib directory where you would like the
# cross-compiler information to be installed.  If you have installed
# from the rpms, this will usually be /usr/lib/mlton.  You must have
# write permission there.

lib="$src/build/lib"

# You shouldn't need to change anything below this line.

rm -rf "$lib/$crossTarget"
mkdir -p "$lib/$crossTarget" || die "Cannot write to $lib."

tmp=/tmp/mlton-add-cross

( cd $src && make dirs )

ssh $machine "rm -rf $tmp && mkdir $tmp"

echo 'Making runtime.' 
( cd $src && tar cf - bin runtime ) | 
	ssh $machine "cd $tmp && tar xf - && cd runtime && make clean all"
ssh $machine "cd $tmp/runtime && tar cf - *.a" | 
	( cd $lib/$crossTarget && tar xf - )
( cd $src &&
	make TARGET=$crossTarget TARGET_ARCH=$crossArch TARGET_OS=$crossOS \
		targetmap )
( cd $src/runtime && make clean )

exe='print-constants'
echo "Compiling and running print-constants on $machine."
cd $original
$src/build/bin/mlton -build-constants true |
	ssh $machine "cd $tmp/runtime &&
			cat >$exe.c && 
			gcc -I. -o $exe $exe.c libmlton.a && 
			./$exe" \
		>"$lib/$crossTarget/constants"

exit 0
ssh $machine "rm -rf $tmp"


