#!/bin/sh

target='unix-386'		# default target

T3XDIR=/home/anthk/t3x/t3x0/sw/lib

# First try to figure out things automatically.
#
CFLAGS=""

case `uname -m` in
	amd64|x86_64)	CFLAGS=$CFLAGS" -m32"
			target="unix-386" ;;
	arm) 		target="unix-armv7" ;;
esac

case `uname` in
	OpenBSD)	CFLAGS=$CFLAGS" -fPIC" ;;
esac

# If this fails, add flags and/or target here.
#

# target=''

# CFLAGS=$CFLAGS" -m32"			# on x86 64-bit systems
# CFLAGS=$CFLAGS" -static"		# in case all else fails
# CFLAGS=$CFLAGS" -fPIC"		# get rid of stupid linker errors
# CFLAGS=$CFLAGS" -Wl,-z,notext"	# get rid of stupid linker errors

cc=cc		# C compiler to compile the lib and do the linking

########## nothing to configure past this line ##########

tcvm=`which tcvm`

bytecode=no
externs=""

targets=""
for x in tcvm unix-386 unix-armv6 unix-armv7 fbsd-386 dos cpm; do
	if [ -f $T3XDIR/tx-$x ]; then
		targets="$targets $x"
	fi
done

if [ "$targets" = "" ]; then
	target="tcvm"
	bytecode="yes"
	for x in tcvm dos cpm; do
		if [ -f $T3XDIR/tx-$x.tc ]; then
			targets="$targets $x"
		fi
	done
fi

usage() {
	echo \
	"Usage: `basename $0` [-bc] [-t target] [-e extern] infile [outfile]"
	echo "       targets:$targets"
	echo "       -b - use bytecode compiler (implies -t tcvm)"
	echo "       -c - link curses library (Unix only)"
	exit 1
}

if [ "$tcvm" = "" ]; then
	echo "$0: error: TCVM not installed"
	exit 1
fi

if [ "$1" = "" ]; then usage; fi

while true; do
	case $1 in
	-t)	target=$2; shift 2 ;;
	-e)	externs="$externs $2"; shift 2 ;;
	-c)	externs="$externs $T3XDIR/console.c -lcurses"
		shift ;;
	-b)	bytecode=yes; target=tcvm; shift ;;
	-*)	usage ;;
	*)	break ;;
	esac
done

if [ ! -e $T3XDIR/tx-$target ]; then
	if [ $bytecode = yes -a ! -e $T3XDIR/tx-$target.tc ]; then
		echo "$0: no such target: $target"
		exit 1
	fi
fi

out=${2:-$1}

if [ $bytecode = no ]; then
	$T3XDIR/tx-$target $1 $out
	if [ $? != 0 ]; then exit 1; fi
	if [ "$target" = "fbsd-386" ]; then
		as -32 -o $out.o $out.s
		ld -o $out $out.o $externs
		strip $out
		rm -f $out.s $out.o
	fi
	if [	"$target" = "unix-386" -o \
		"$target" = "unix-armv6" -o \
		"$target" = "unix-armv7" \
	]; then
		$cc $CFLAGS -s -o $out $out.s $T3XDIR/unx32lib.c $externs
		rm -f $out.s
	fi
elif [ -x $T3XDIR/tx-$target.tc ]; then
	$tcvm $T3XDIR/tx-$target.tc $1 $out
else
	if [ "$target" != "tcvm" ]; then
		echo "$0: target not installed: $target"
		exit 1
	fi
	$tcvm $T3XDIR/txtrn.tc $1 $out
fi
