# Common shell routines for Java launcher scripts

## FindJavaBin
# Locates the Java binary under the JDK/JRE directory
# as specified in the JAVA_HOME variable.
# Sets the JAVA_BIN global variable to the pathname
# of the Java VM executable, if found.
# If no executable was found a nonzero is returned.
FindJavaBin()
{
    local bin
    for bin in "$JAVA_HOME/jre/bin/java" "$JAVA_HOME/bin/java"; do
	if test -x "$bin"; then
	    JAVA_BIN=$bin
	    return 0
	fi
    done
    return 1
}

## FindJVM
# Checks the JAVA_HOME environment variable.
# If the variable is not set, searches for a JRE installation
# among predefined paths and exports JAVA_HOME as appropriate.
# The function also sets the JAVA_BIN global variable to the pathname
# of the Java VM executable, if found.
# Returns a nonzero status if neither JRE location nor the
# fallback executable provided by jdkgcj has been found.
FindJVM()
{
    local home bin
    if test -n "$JAVA_HOME" && FindJavaBin; then
	return $?
    fi
    for home in '@LIBDIR@'/{jvm/java,j2se,jdk} /usr/java/jdk*/jre/bin/java '@LIB64DIR@'/{jvm/java,j2se,jdk}; do
	test -d "$home" || continue
	JAVA_HOME=$home
	if FindJavaBin; then
	    export JAVA_HOME
	    return 0
	fi
	unset JAVA_HOME
    done

    # search for JRE
    for bin in /usr/lib/jvm/jre/bin/java /usr/java/jre*/bin/java; do
	if test -x "$bin"; then
	    JAVA_BIN=$bin
	    return 0
	fi
    done

    # Fall back for jdkgcj
    for bin in {'@LIBDIR@','@LIB64DIR@'}/jdkgcj/bin/java; do
	if test -x "$bin"; then
	    JAVA_BIN=$bin
	    return 0
	fi
    done
    return 1
}

## AddToClasspath
# Adds the list of specified names
# to the CLASSPATH environment variable.
# Names can be absolute or relative; if a relative name is specified, it is
# prefixed with the system Java library directory.
# Only the names that exist as files or directories will
# be added.
#
AddToClasspath()
{
    local javalibdir=@JAVADIR@
    local p

    for p in "$@"; do
	case "$p" in
	    /*) ;;
	    *)  p=$javalibdir/$p ;;
	esac
	if [ ! -e "$p" ]; then
	    continue
	fi
	if [ -n "$CLASSPATH" ]; then
	    CLASSPATH=$CLASSPATH:$p
	else
	    CLASSPATH=$p
	    export CLASSPATH
	fi
    done
}
