#!/bin/bash

if [ "${DIB_DEBUG_TRACE:-0}" -gt 0 ]; then
    set -x
fi
set -eu
set -o pipefail

echo "Installing OpenJDK"

default_jdk_version_for_distro () {
    case "$DISTRO_NAME" in
        centos | rhel | ubuntu )
            echo "7"
        ;;
        fedora )
            if [ $(lsb_release -rs) -ge '21' ]; then
                echo "8"
            else
                echo "7"
            fi
        ;;
        centos7 | rhel7 )
            echo "8"
        ;;
        *)
            echo "Unknown OpenJDK distro: $DISTRO_NAME" >&2
            exit 1
        ;;
    esac
}

pkg=openjdk-$(default_jdk_version_for_distro)
pkg=$(pkg-map --element openjdk $pkg)
install-packages $pkg

case "$DISTRO_NAME" in
    ubuntu )
        JRE_PATH=$(update-alternatives --list java)
        JRE_HOME=${JRE_PATH%/bin/java}
        JDK_PATH=$(update-alternatives --list javac)
        JDK_HOME=${JDK_PATH%/bin/javac}
    ;;
    fedora | rhel | rhel7 | centos | centos7 )
        # NOTE: rpm -E "%{java_home}" command returns wrong java home
        # on CentOS, Fedora and RHEL
        JRE_HOME="/usr/lib/jvm/java-openjdk/jre"
        JDK_HOME="/usr/lib/jvm/java-openjdk"
    ;;
esac

setup-java-home $JRE_HOME $JDK_HOME

echo "OpenJDK has been installed"
