#!/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"
name="${MAIN_CLASS_NAME##*/}"
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"
if [ -n "$name" ]; then
	cat > "$name.java"
else
	#input_file="`mktemp ClassXXXXXX.java`"
	#input_file=Class$$.java
	input_file=Program.java
	cat > "$input_file"
	if name="`sed -En 's/^[[:space:]]*public[[:space:]]+class[[:space:]]+([A-Za-z_][A-Za-z_0-9]*).*/\\1/p' \"$input_file\"`" && [ -n "$name" ]; then
		mv "$input_file" "$name.java"
	else
		name="${input_file%.java}"
	fi
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=$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
