#!/bin/bash

# The first existing directory is used for JAVA_HOME if needed.
JVM_SEARCH_DIRS="/usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-sun /usr/java/latest /usr/lib/jvm/jre-1.6.0"

# If JAVA_HOME has not been set, try to determine it.
if [ -z "$JAVA_HOME" ]; then
    # If java is in PATH, use a JAVA_HOME that corresponds to that. This is
    # both consistent with how the upstream startup script works, and how
    # Debian works (read: the use of alternatives to set a system JVM).
    if [ -n "`which java 2> /dev/null`" ]; then
        java=`which java`
        # Dereference symlink(s)
        while true; do
            if [ -h "$java" ]; then
                java=`readlink "$java"`
                continue
            fi
            break
        done
        echo "$java"
        exit 0
    # No JAVA_HOME set and no java found in PATH, search for a JVM.
    else
        for jdir in $JVM_SEARCH_DIRS; do
            if [ -x "$jdir/bin/java" ]; then
                echo "$jdir/bin/java"
                exit 0
            fi
        done
    fi
else
    if [ -x "$JAVA_HOME/bin/java" ]; then
        echo "$JAVA_HOME/bin/java"
        exit 0
    fi
fi

exit 1
