#!/usr/bin/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.

BIGTOP_DEFAULTS_DIR=${BIGTOP_DEFAULTS_DIR-/etc/default}
[ -n "${BIGTOP_DEFAULTS_DIR}" -a -r ${BIGTOP_DEFAULTS_DIR}/bigtop-utils ] && . ${BIGTOP_DEFAULTS_DIR}/bigtop-utils

# Ensure that JAVA_HOME has already been found
if [ -z "$JAVA_HOME" ]; then
    echo "JAVA_HOME must be set before calling bigtop-detect-javalibs"
    exit 1
fi

# Check the known external path first
known_external_cacerts_path="/etc/pki/ca-trust/extracted/java/cacerts"
if [ -f "$known_external_cacerts_path" ]; then
    cacerts_path=$known_external_cacerts_path
else
    # Use find to search for cacerts file under JAVA_HOME and follow symbolic links
    cacerts_path=$(find "${JAVA_HOME}" -type l -name cacerts -exec readlink -f {} \; 2>/dev/null)
    # If not found as a symbolic link, try to find it as a regular file
    if [ -z "$cacerts_path" ]; then
        cacerts_path=$(find "${JAVA_HOME}" -type f -name cacerts 2>/dev/null)
    fi

    # Lastly, check the common locations directly if still not found
    if [ -z "$cacerts_path" ]; then
        if [ -L "${JAVA_HOME}/lib/security/cacerts" ]; then
            cacerts_path=$(readlink -f "${JAVA_HOME}/lib/security/cacerts")
        elif [ -L "${JAVA_HOME}/jre/lib/security/cacerts" ]; then
            cacerts_path=$(readlink -f "${JAVA_HOME}/jre/lib/security/cacerts")
        fi
    fi
fi

# Check if cacerts_path is not empty
if [ -n "$cacerts_path" ] && [ -f "$cacerts_path" ]; then
    echo "$cacerts_path"
else
    echo "Unable to find cacerts in JDK at ${JAVA_HOME}"
    exit 1
fi