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

conftool() {
  CLASS=org.apache.hive.conftool.ConfCli

  # Detect Java major version reliably from 'java --version'
  JAVA_CMD=${JAVA_HOME:+$JAVA_HOME/bin/java}
  JAVA_CMD=${JAVA_CMD:-java}
  JAVA_VER=$($JAVA_CMD --version 2>&1 | head -n1 | awk '{print $2}' | cut -d. -f1)

  # Add --add-opens flags only for Java 17+
  EXTRA_OPTS=""
  if [ "$JAVA_VER" -ge 17 ]; then
    EXTRA_OPTS="--add-opens=java.base/java.lang=ALL-UNNAMED \
                --add-opens=java.base/java.lang.reflect=ALL-UNNAMED \
                --add-opens=java.base/java.io=ALL-UNNAMED \
                --add-opens=java.base/java.util=ALL-UNNAMED"
  fi

  # Launch conftool
  $JAVA_CMD ${MAPR_COMMON_JAVA_OPTS} ${EXTRA_OPTS} \
       -Dlog4j.configurationFile=${HIVE_CONF}/${LOG_FILE} \
       -cp ${HADOOP_CLASSPATH} \
       $CLASS "$@"
}

HIVE_HOME="$(cd "$(dirname "${BASH_SOURCE[0]}" )/.." && pwd)"
HIVE_LIB=${HIVE_HOME}/lib
HIVE_CONF=${HIVE_HOME}/conf
LOG_FILE="conftool-log4j2.properties"
MAPR_HOME="${BASEMAPR:-/opt/mapr}"
export MAPR_TICKETFILE_LOCATION="${MAPR_HOME}/conf/mapruserticket"

if [ "$HADOOP_CLASSPATH" != "" ]; then
  HADOOP_CLASSPATH="$HIVE_LIB/*:${HADOOP_CLASSPATH}"
else
  HADOOP_CLASSPATH="$HIVE_LIB/*":$(hadoop classpath)
fi

conftool "$@"
