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

# Resolve our absolute path
# resolve links - $0 may be a softlink
function get_canonical_dir() {
  target="$1"
  canonical_name=`readlink -f ${target} 2>/dev/null`
  if [[ $? -eq 0 ]]; then
    canonical_dir=`dirname $canonical_name`
    echo ${canonical_dir}
    return
  fi

  # Mac has no readlink -f
  cd `dirname ${target}`
  target=`basename ${target}`

  # chase down the symlinks
  while [ -L ${target} ]; do
    target=`readlink ${target}`
    cd `dirname ${target}`
    target=`basename ${target}`
  done

  canonical_dir=`pwd -P`
  ret=${canonical_dir}
  echo $ret
}

# convert relative path to absolute path
bin=`get_canonical_dir "${BASH_SOURCE-$0}"`
script=`basename "$0"`
bin=`unset CDPATH; cd "$bin"; pwd`
this="$bin/$script"
#to preserve value of 'this' since any other file that defines 'this' and is sourced
#here (e.g. hcat-config.sh) will overwrite it
this_hcat=$this

export BASEMAPR=${MAPR_HOME:-/opt/mapr}
env=${BASEMAPR}/conf/env.sh
[ -f $env ] && . $env
HADOOP_DIR=$(get_canonical_dir "/usr/bin/hadoop")
HADOOP_DIR=`dirname $HADOOP_DIR`
export HADOOP_HOME=${HADOOP_HOME:-$HADOOP_DIR}

function echoerr() {
    echo "${this_hcat}: $@" 1>&2
}

if [ -e "$bin/../libexec/hcat-config.sh" ]; then
  . "$bin"/../libexec/hcat-config.sh
else
  . "$bin"/hcat-config.sh
fi

# filter debug command line parameter
debug=false
dump_classpath=false

for f in $@; do
     if [[ $f = "-secretDebugCmd" ]]; then
        debug=true
     else
        remaining="${remaining} $f"
     fi
     if [[ $f = "-classpath" ]]; then
        dump_classpath=true
     fi
done

# derive HIVE_HOME relative to hcat binary location
HIVE_DIR="$bin/../../"

# HIVE_HOME env variable overrides hive in the path
HIVE_HOME=${HIVE_HOME:-$HIVE_DIR}

#if hive is not in path and not set by env, set it to default in build tree
if [ ! -n "${HIVE_HOME}" ]; then
  HIVE_HOME="${bin}/../.."
  echoerr "HIVE_HOME is not defined; assuming ${HIVE_HOME}";
fi

if [ "$HIVE_HOME" == "" ]; then
  echo "${this_hcat}: Cannot find hive installation: \$HIVE_HOME must be set or hive must be in the path";
  exit 4;
fi

if [ "$HIVE_HOME" == '/usr' ] || [ "$HIVE_HOME" == '/usr/' ]; then
  #this would be a hive rpm install, bigtop rpm  has HIVE_HOME dir
  #structure in /usr/lib/hive. Use that if the dir structure looks good
  if [ -d '/usr/lib/hive/conf' ] && [ -d '/usr/lib/hive/lib' ]; then
    HIVE_HOME='/usr/lib/hive/';
  fi
fi



HIVE_LIB_DIR=${HIVE_HOME}/lib
if [ ! -d "$HIVE_LIB_DIR" ]; then
  echo "${this_hcat}: Cannot find lib dir within HIVE_HOME : $HIVE_LIB_DIR";
  exit 4;
fi

HIVE_CONF_DIR=${HIVE_CONF_DIR:-$HIVE_HOME/conf}
if [ ! -d "$HIVE_CONF_DIR" ]; then
  echo "${this_hcat}: Cannot find conf dir within HIVE_HOME : $HIVE_CONF_DIR";
  exit 4;
fi


# Find our hcatalog jar
shopt -s extglob
if [ "$(ls -1 $HCAT_PREFIX/share/hcatalog/hive-hcatalog-core-[0-9]*.jar | wc -l)" -ne 1 ]; then
    echo "Error: did not find exactly one hive-hcatalog-core jar in $HCAT_PREFIX/share/hcatalog"
    exit 1
fi
HCAT_JAR=`ls $HCAT_PREFIX/share/hcatalog/hive-hcatalog-core-[0-9]*.jar`

# Add all of the other jars to our classpath
for jar in ${HIVE_LIB_DIR}/*.jar ; do
	HADOOP_CLASSPATH=$HADOOP_CLASSPATH:$jar
done

# add the auxillary jars such as serdes
if [ -d "${HIVE_AUX_JARS_PATH}" ]; then
  for f in ${HIVE_AUX_JARS_PATH}/*.jar; do
    if [[ ! -f $f ]]; then
        continue;
    fi
    HADOOP_CLASSPATH=${HADOOP_CLASSPATH}:$f
  done
elif [ "${HIVE_AUX_JARS_PATH}" != "" ]; then
  HIVE_AUX_JARS_PATH=`echo $HIVE_AUX_JARS_PATH | sed 's/,/:/g'`
  HADOOP_CLASSPATH=$HADOOP_CLASSPATH:$HIVE_AUX_JARS_PATH
fi

# also pass hive classpath to hadoop
if [ "$HIVE_CLASSPATH" != "" ]; then
  export HADOOP_CLASSPATH="${HADOOP_CLASSPATH}:${HIVE_CLASSPATH}";
fi

# Put external jars, hcat jar, and config file in the classpath
HADOOP_CLASSPATH=${HIVE_CONF_DIR}:${HADOOP_CLASSPATH}:${HCAT_CLASSPATH}:${HCAT_JAR}

# Look for HBase in a MapR-compatible way. Avoid thrift version
# conflict with modern versions of HBase.
export BASEMAPR=${BASEMAPR:-"/opt/mapr"}
if [ -f $BASEMAPR/hbase/hbaseversion ]; then
   MAPR_HBASE_VERSION=`cat $BASEMAPR/hbase/hbaseversion 2>/dev/null`
else
   MAPR_HBASE_VERSION="*"

fi

MAPR_HBASE_HOME=${MAPR_HBASE_HOME:-"${BASEMAPR}/hbase/hbase-${MAPR_HBASE_VERSION}"}
MAPR_HBASE_JAR=$(find $BASEMAPR/hbase -regextype posix-extended -regex ".*\/hbase-${MAPR_HBASE_VERSION}-.*[^s]\.jar" -print 2> /dev/null)
MAPR_HBASE_TEST_JAR=$(find $BASEMAPR/hbase -regextype posix-extended -regex ".*\/hbase-${MAPR_HBASE_VERSION}.*tests\.jar" -print 2> /dev/null)
MAPR_HBASE_CONF_DIR=${MAPR_HBASE_CONF_DIR:-"${MAPR_HBASE_HOME}/conf"}

if [ -d ${MAPR_HBASE_HOME} ] ; then
   for jar in $(find $MAPR_HBASE_HOME \! \( -path $MAPR_HBASE_HOME/tmp -prune \) -name '*.jar' -not -name '*thrift*'); do
      HBASE_CLASSPATH=$HBASE_CLASSPATH:${jar}
   done
   export HADOOP_CLASSPATH="${HADOOP_CLASSPATH}:${HBASE_CLASSPATH}"
fi
if [ -d $MAPR_HBASE_CONF_DIR ] ; then
    HADOOP_CLASSPATH="${HADOOP_CLASSPATH}:${MAPR_HBASE_JAR}:${MAPR_HBASE_TEST_JAR}:${MAPR_HBASE_CONF_DIR}"
fi

export HADOOP_CLASSPATH=$HADOOP_CLASSPATH

export HADOOP_OPTS="$HADOOP_OPTS ${MAPR_HIVE_LOGIN_OPTS}"


# get the yarn version
if [ -f $BASEMAPR/conf/hadoop_version ];then
  MAPR_YARN_VERSION=`cat $BASEMAPR/conf/hadoop_version | grep yarn_version | awk -F'=' '{print $2}'`
  HADOOP_PREFIX=$BASEMAPR/hadoop/hadoop-$MAPR_YARN_VERSION
else
  HADOOP_PREFIX=$HADOOP_PREFIX
fi

if [ ! -d "${HADOOP_LIBEXEC_DIR}" ]; then
  export HADOOP_LIBEXEC_DIR=$HADOOP_PREFIX/libexec;
fi

# run it
if [ "$debug" == "true" ]; then
	echo "Would run:"
	echo "exec $HADOOP_PREFIX/bin/hadoop jar $HCAT_JAR org.apache.hive.hcatalog.cli.HCatCli $remaining"
	echo "with HADOOP_CLASSPATH set to ($HADOOP_CLASSPATH)"
	echo "and HADOOP_OPTS set to ($HADOOP_OPTS)"
elif [ "$dump_classpath" == "true" ]; then
    echo $HADOOP_CLASSPATH
else
	exec $HADOOP_PREFIX/bin/hadoop jar  $HCAT_JAR org.apache.hive.hcatalog.cli.HCatCli "$@"
fi

