#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


# Override JAVA_HOME in the file below if you want to disable
# automatic JAVA_HOME detection
[ -r /etc/default/bigtop-utils ] && . /etc/default/bigtop-utils

JAVA6_HOME_CANDIDATES='\
    /usr/lib/j2sdk1.6-sun \
    /usr/lib/jvm/java-6-sun \
    /usr/lib/jvm/java-1.6.0-sun-1.6.0.* \
    /usr/lib/jvm/java-1.6.0-sun-1.6.0.*/jre/ \
    /usr/lib/jvm/j2sdk1.6-oracle \
    /usr/lib/jvm/j2sdk1.6-oracle/jre \
    /usr/java/jdk1.6* \
    /usr/java/jre1.6*'

OPENJAVA6_HOME_CANDIDATES='\
    /usr/lib/jvm/java-1.6.0-openjdk \
    /usr/lib/jvm/java-1.6.0-openjdk-* \
    /usr/lib/jvm/jre-1.6.0-openjdk*'

JAVA7_HOME_CANDIDATES='\
    /usr/java/jdk1.7* \
    /usr/java/jre1.7* \
    /usr/lib/jvm/j2sdk1.7-oracle \
    /usr/lib/jvm/j2sdk1.7-oracle/jre \
    /usr/lib/jvm/java-7-oracle*'

OPENJAVA7_HOME_CANDIDATES='\
    /usr/lib/jvm/java-1.7.0-openjdk* \
    /usr/lib/jvm/java-7-openjdk*'

MISCJAVA_HOME_CANDIDATES='\
    /Library/Java/Home \
    /usr/java/default \
    /usr/lib/jvm/default-java \
    /usr/lib/jvm/java-openjdk \
    /usr/lib/jvm/jre-openjdk'

case $BIGTOP_JAVA_MAJOR in
  6) JAVA_HOME_CANDIDATES="$JAVA6_HOME_CANDIDATES"
     ;;
  7) JAVA_HOME_CANDIDATES="$JAVA7_HOME_CANDIDATES $OPENJAVA7_HOME_CANDIDATES"
     ;;
  *) JAVA_HOME_CANDIDATES="$JAVA6_HOME_CANDIDATES     \
                           $JAVA7_HOME_CANDIDATES     \
                           $MISCJAVA_HOME_CANDIDATES  \
                           $OPENJAVA7_HOME_CANDIDATES \
                           $OPENJAVA6_HOME_CANDIDATES"
     ;;
esac

# attempt to find java
if [ -z "$JAVA_HOME" ]; then
  for candidate_regex in $JAVA_HOME_CANDIDATES ; do
      for candidate in `ls -rd $candidate_regex 2>/dev/null`; do
        if [ -e $candidate/bin/java ]; then
          export JAVA_HOME=$candidate
          break 2
        fi
      done
  done
fi

