#!/bin/sh

[ "$1" = --version ] && exec /usr/local/bin/x86_64-unknown-freebsd12-gcj-4.7.4 --version

flags="-Wall -fno-common --pipe -x java"
[ -n "$DEBUG" ] && flags="$flags -g"
[ -n "$OPTIMIZATION" ] && flags="$flags -O$OPTIMIZATION"
for d in $DEFINE; do flags="-D $d $flags"; done
for d in $UNDEFINE; do flags="-U $d $flags"; done
[ -n "$VERBOSE" ] && flags="$flags -v"
set -e
# GNU Java requires Java source file be a regular file with suffix '.java'
TMPDIR="`mktemp -d`"
trap 'cd / && rm -rf "$TMPDIR"' EXIT
cd "$TMPDIR"
cat > Program.java
if name="`grep -m 1 -Eo '^[[:space:]]*public[[:space:]]+((abstract|final)[[:space:]]+)*class[[:space:]]+[A-Za-z_][A-Za-z_0-9]*' Program.java`"; then
	name="${name##*[[:space:]]}"
	mv Program.java "$name.java"
	[ -z "$MAIN_CLASS_NAME" ] && MAIN_CLASS_NAME="$name"
elif name="${MAIN_CLASS_NAME##*/}" && [ -n "$name" ]; then
	mv Program.java "$name.java"
elif name="`grep -m 1 -Eo '^[[:space:]]*((abstract|final)[[:space:]]+)*class[[:space:]]+([A-Za-z_][A-Za-z_0-9]*)' Program.java`"; then
	name="${name##*[[:space:]]}"
	mv Program.java "$name.java"
	MAIN_CLASS_NAME="$name"
else
	name=Program
	MAIN_CLASS_NAME=Program
fi
case "$ONLY_STAGE" in
	E|S)
		/usr/local/bin/x86_64-unknown-freebsd12-gcj-4.7.4 -$ONLY_STAGE $flags "$@" "$name.java" -o -
		;;
	"")
		/usr/local/bin/x86_64-unknown-freebsd12-gcj-4.7.4 $flags "$@" "--main=$MAIN_CLASS_NAME" "$name.java" -o "$name"
		cat "$name"
		;;
	c)
		/usr/local/bin/x86_64-unknown-freebsd12-gcj-4.7.4 -c $flags "$@" "$name.java" -o "$name.o"
		cat "$name.o"
		;;
esac
