#
# Java classpath editing shell utilities
#
# IMPORTANT: In order to be capable of modifying the classpath of your
# current shell these commands must be sourced into the current shell.
# e.g. 
#     . /usr/local/common/java_classpath_util.sh
#
# By Pat Niemeyer (pat@pat.net)
# 

#
# Decompose the classpath into an editor session, then recompose it.
#
editclasspath() {
	tmp=/tmp/cp.$$
	tmpcopy=/tmp/cp.2.$$
	/bin/echo "# Edit the items in your classpath, then save and quit." > $tmp
	/bin/echo "# Note: these changes will only affect your current shell." >> $tmp
	/bin/echo >> $tmp
	/bin/echo $CLASSPATH | tr ':' '\n'  >> $tmp

	if [ "$1" ]; then
		/bin/echo "# Adding these paths..." >> $tmp

		for p in $*; 
		do
			/bin/echo $p >> $tmp
		done
	fi

	# copy the file for change comparison after we edit
	/bin/cp $tmp $tmpcopy 

	${EDITOR:=/usr/bin/vi} $tmp

	# Note: I think this "newer" comparison only works if the time span
	# is greater than one second...  (from experimentation).
	#
	if [ $tmp -nt $tmpcopy ]; then 
		:
	else 
		echo "Edit aborted:  No changes to classpath."
		return
	fi

	newcp=`cat $tmp | sed '/^#/d;/^[ \t]*$/d' | tr '\n' ':'`
	# remove trailing colon
	newcp=`echo $newcp | sed "s/:$//"`

	if [ "$newcp" = "$CLASSPATH" ] ; then
		/bin/echo "No changes detected for CLASSPATH."
		return
	else
		/bin/echo "CLASSPATH modified."
	fi 
	
	CLASSPATH=$newcp
	export CLASSPATH
	rm $tmp $tmpcopy
}

#
# Call editclasspath, adding the specified paths to the list
#
addclasspath() {
	if [ ! "$1" ]; then
		/bin/echo "usage: addclasspath path [ path ] [ ... ]"
		return
	fi

	#
	# Fix up relative path components
	#
	newpath=""
	for p in $*
	do
		p=`echo $p | sed "s@^./@@"`
		if dirname $p | grep '^/' > /dev/null; then
			: 
		else
			p="`pwd`/$p"
		fi
		newpath="$newpath $p"
	done

	editclasspath $newpath
}

#
# This is just a quick, hardcoded list for now.
# In a real package system the list and descriptions would be dynamic.
#
setjdk() {
	/bin/echo "# Choose a version of the JDK"
	/bin/echo "1) JDK 1.1"
	/bin/echo "2) JDK 1.2"
	/bin/echo "3) JDK 1.3"
	/bin/echo "4) JDK 1.4"
	/bin/echo "q|n|^C) No Change"
	/bin/echo
	/bin/echo "Choice:  \c"
	read choice

	case $choice in 
		1) JAVA_HOME=/usr/java1.1;;
		2) JAVA_HOME=/usr/java1.2;;
		3) JAVA_HOME=/pkg/j2sdk1.3.0;;
		4) JAVA_HOME=/pkg/j2sdk1.4.0;;
		q) echo 'No Change...'; return;;
	esac

	JAVAHOME=$JAVA_HOME  # do we really need this?
	PATH=$JAVA_HOME/bin:$PATH
	export JAVAHOME JAVA_HOME PAH
}

export editclasspath addclasspath setjdk

