#!/bin/sh
# Emulate the jdk javac command using gcj
# (c) 2002-2003 Bernhard Rosenkraenzer <bero@arklinux.org>

GCC=`gcj --version |head -n1 |awk '{ print $3; }'`

clp="/usr/share/java/libgcj-$GCC.jar"
if [ ! -f "$clp" ]; then
	GCC="${GCC%.*}"
	clp="/usr/share/java/libgcj-$GCC.jar"
fi

if [ -n "$CLASSPATH" ]; then
	clp="$CLASSPATH:$clp"
fi

[ -n "${GCC##4.[3-9]*}" -a -n "${GCC##5*}" ] ||
	exec gcj -C -classpath "$clp" "$@"

unset DEST || :
while [ "$#" != 0 ]; do
	if [ "$1" = "-J-version" ]; then
		echo 'java version "1.3.1"' 1>&2
		echo 'jdkgcj 0.3.2 (http://www.arklinux.org/projects/jdkgcj)'
		gcj --version 1>&2
		exit 0
	elif [ "$1" = "-classpath" ]; then
		shift
		clp="`echo $1 | sed \"s~.*/lib/rt.jar~/usr/share/java/libgcj-$GCC.jar~\"`"
	elif [ "$1" = "-d" ]; then
		# Class files will be put into this directory
		shift
		DEST="$1"
	elif [ "$1" = "-target" ]; then
		# FIXME: What precisely does -target do?
		echo "Warning: Ignoring -target $1" >&2
		shift
	elif [ "`echo $1 |cut -b1`" = "-" ]; then
		# Yuck. Unknown parameter. Let's pretend nothing happened.
		echo "Warning: $1 not understood. Ignoring." >&2
	else
		files="$files $1"
	fi
	shift
done
if ! echo $clp |grep -q /usr/share/java/libgcj-$GCC.jar; then
	# We NEED this
	clp="$clp:/usr/share/java/libgcj-$GCC.jar"
fi
gcj -C -classpath "$clp" $files
if [ "$?" != "0" ]; then
	exit $?
fi
if [ -n "$DEST" ]; then
	for i in $files; do
		[ -e "$i" ] || continue # skip parameters...
		classes="`jv-scan --list-class $i`"
		dir="`dirname $i`"
		for class in $classes; do
			file="`echo $class |sed -e 's,\.,/,g'`"
			classname="`basename $file`"
			tree="`dirname $file`"
			if [ -e "$dir/${classname}.class" ]; then
				mkdir -p "$DEST/$tree"
				if ! ERR="`LANG=C mv \"$dir/${classname}.class\" \"$DEST/$tree\" 2>&1`"; then
					if ! echo $ERR |grep -q "are the same file"; then
						echo $ERR >&2
						exit 1
					fi
				fi
			fi
		done
	done
fi
exit 0
