#!/bin/bash
#  Copyright (c) 2017, 2020, Oracle and/or its affiliates.
#  This software code contains proprietary information
#  and should be treated as confidential.
#
#  Common global constants and methods

# Constants

# Gateway certficate alias for keystore.
# Do not change this without changing the constant 
# defined in the DataSignerFactory class 
OSGD_GW_ALIAS="OSGD_GATEWAY"

# The default location of Java
DEFAULT_GW_JAVA_HOME="/usr/lib/jvm/jre-11/bin"
GW_JAVA_HOME_FILE="/var/info/gw-java-home"
REQUIRED_JAVA_VERSION="11"

# Setup environment if not already set
[ -z ${INSTDIR} ] && {
    INSTDIR="/opt/SUNWsgdg"
} 

#
# Returns the path to Java bin to use for the GateWay. 
# Parameters: 
#     - the installdir of the Gateway.
# Returns:
#     - the location of java bin
#
GetJavaBinDir()
{
    javabin="$(GetJavaHome "$1")"
    echo "${javabin}/bin"
}

#
# Returns the path to Java home to use for the Gateway.
# Parameters: 
#     - the installdir of the Gateway.
# Returns:
#     - the location of java home
#
GetJavaHome()
{
    if [ $# -ne 1 ]
    then
        return
    fi

    INSTALL_DIR="$1"

    # Read the java home file if it exists
    selectedJavaHome="$(ReadJavaHomeFile ${INSTALL_DIR})"
    if [ -n "${selectedJavaHome}" ] && [ -x "${selectedJavaHome}/bin/java" ]
    then
        echo "${selectedJavaHome}"
        return
    fi

    # No java home file, so look at the alternatives
    options="$(alternatives --display java | grep -e '.*/bin/java\($\|[^a-z]\).*')"
    current_java="$(echo "${options}" | head -1 | awk '{print $NF}')"

    # Check whether the current java is valid
    version="$(CheckJavaVersion "${current_java}" "${REQUIRED_JAVA_VERSION}")"
    if [ -n "${version}" ]
    then
        echo "$(WriteJavaHomeFile "${INSTALL_DIR}" "${current_java}")"
        return
    fi

    # Check all available versions to find a candidate
    echo "${options}" | head -n -1 | tail -n +2 | awk '{print $1}' |
    while read -r avail_java
    do
        version="$(CheckJavaVersion "${avail_java}" "${REQUIRED_JAVA_VERSION}")"
        if [ -n "${version}" ]
        then
            echo "$(WriteJavaHomeFile "${INSTALL_DIR}" "${avail_java}")"
            return
        fi
    done

    # No possible candidates - this should not happen as the rpm
    # dependency should enforce the correct version of java.
}

#
# Reads the java directory from the Gateway Java home file.
# Parameters: 
#     - the installdir of the Gateway.
# Returns:
#     - the location of java home or nothing if the 
#       file is missing or invalid.
ReadJavaHomeFile()
{
    if [ $# -ne 1 ]
    then
        return
    fi

    INSTALL_DIR="$1"
    javafile="${INSTALL_DIR}/${GW_JAVA_HOME_FILE}"

    # Read the first line in the file. 
    # There should only be one line, but ignore others if there are more.
    if [ -f ${javafile} ]
    then
        javapath=`head -1 ${javafile}`
        # return the value
        echo "${javapath}"
    fi
}

#
# Writes a java directory to the Gateway Java home file.
# Parameters: 
#     - the installdir of the Gateway.
#     - the java binary path to write to the file
# Returns:
#     - the value written to the file
#
WriteJavaHomeFile()
{
    if [ $# -ne 2 ]
    then
        return
    fi

    INSTALL_DIR="$1"
    JAVA_BIN_PATH="$2"

    java_home="$(echo "${JAVA_BIN_PATH}" | sed -e 's|/bin/java||g')"
    # Add java home to the file
    echo "${java_home}" > "${INSTALL_DIR}/${GW_JAVA_HOME_FILE}"
    # Give full read/write permissions
    chmod 644 "${INSTALL_DIR}/${GW_JAVA_HOME_FILE}"
    # Return java home
    echo "${java_home}"
}

#
# Deletes the Gateway Java home file
# Parameters:
#     - the installdir of the Gateway
#
DeleteJavaHomeFile()
{
    if [ $# -ne 1 ]
    then
        return
    fi

    INSTALL_DIR="$1"
    javafile="${INSTALL_DIR}/${GW_JAVA_HOME_FILE}"

    rm -f "${javafile}" 2>/dev/null
}

#
# Checks the version of the given java matches that required.
# Parameters:
#    - the java binary to test
#    - the expected version
# Returns:
#    - the version if the binary matches and an empty string if not.
CheckJavaVersion()
{
    if [ $# -ne 2 ]
    then
        return
    fi

    JAVA_PATH="$1"
    EXPECTED_VERSION="$2"

    version="$(${JAVA_PATH} -version 2>&1 | grep version | tr '"' ' ' | awk '{print $3}' | grep "^${EXPECTED_VERSION}")"

    echo "${version}"
}

# If the reset flag is set delete the existing file
if [ -n "${RESET_GW_JAVA_HOME}" ]
then
    DeleteJavaHomeFile "${INSTDIR}"
fi

GW_JAVA_HOME="$(GetJavaHome "${INSTDIR}")"
# Check whether a suitable version of Java has been found
if [ -z "${GW_JAVA_HOME}" ]
then
    # No JVM so fallback to hardcoded path provided by the 
    # java-11 RPM dependency.
    GW_JAVA_HOME="${DEFAULT_GW_JAVA_HOME}"
fi

GW_JAVA_DIR="${GW_JAVA_HOME}/bin"

