#!/bin/bash

# Set JAVA_HOME to working JDK or JRE
# If not set we'll try to guess the JAVA_HOME
# from java binary if on the PATH
if [ -z "$JAVA_HOME" ]; then
    JAVA_BINARY="`which java 2>/dev/null || type java 2>&1`"
    while [ -h "$JAVA_BINARY" ]; do
        ls=`ls -ld "$JAVA_BINARY"`
        link=`expr "$ls" : '.*-> \(.*\)$'`
        if expr "$link" : '/.*' > /dev/null; then
            JAVA_BINARY="$link"
        else
            JAVA_BINARY="`dirname $JAVA_BINARY`/$link"
        fi
    done
    test -x "$JAVA_BINARY" && JAVA_HOME="`dirname $JAVA_BINARY`"
    test ".$JAVA_HOME" != . && JAVA_HOME=`cd "$JAVA_HOME/.." >/dev/null; pwd`
else
    JAVA_BINARY="$JAVA_HOME/bin/java"
fi

if [ -z "$JRE_HOME" ]; then
    if [ -z "$JAVA_HOME" ]; then
        # If JRE_HOME and JAVA_HOME are not defined, edit this line to define JRE_HOME
        JRE_HOME=
    elif [ -n "$JAVA_HOME" ] && [ -x "$JAVA_HOME/jre/bin/java" ]; then
        # If JAVA_HOME points to a valid JDK, use its JRE
        JRE_HOME="$JAVA_HOME/jre"
    elif [ -n "$JAVA_HOME" ] && [ -x "$JAVA_HOME/bin/java" ]; then
        # If JAVA_HOME appears to point to a JRE and not a JDK use this anyway
        JRE_HOME="$JAVA_HOME"
    fi
fi

# By this line, JRE_HOME should be defined
if [ -z "$JRE_HOME" ]; then
    echo "Neither the JAVA_HOME nor the JRE_HOME environment variable is defined"
    echo "Edit set-jre-home.sh and define JRE_HOME"
    return 1
fi

if [ -n "$JRE_HOME" ] && [ -x "$JRE_HOME/bin/java" ]; then
    # Found java executable in JRE_HOME
    JAVA_BINARY="$JRE_HOME/bin/java"
    JAVA_VERSION=$("$JAVA_BINARY" -version 2>&1 | awk -F '"' '/version/ {print $2}')
    if [ "$JAVA_VERSION" \< "1.8" ]; then
        echo "JRE_HOME '$JRE_HOME' is Java $JAVA_VERSION"
        echo "Atlassian Bitbucket requires Java 8 to run"
        echo "Set JRE_HOME to a Java 8 JRE and try again"
        return 1
    fi
else
    # If JRE_HOME/bin/java is not an executable, JRE_HOME is not valid
    echo "The JRE_HOME environment variable is not defined correctly"
    echo "This environment variable is needed to run this program"
    echo "Edit set-jre-home.sh and define JRE_HOME"
    return 1
fi

# This ensures that JAVA_HOME and JRE_HOME are consistent so that
# both Bitbucket and the bundled search server use the same JVM.
JAVA_HOME=$JRE_HOME

# If we make it here, the Java environment looks good
export JRE_HOME
export JAVA_HOME
export JAVA_BINARY
export JAVA_VERSION
