#!/bin/bash
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
# Runs chive jar.

# Time marker for both stderr and stdout
date; date 1>&2

# debug
set -x
echo "Running on: $(hostname -f) ($(hostname -i))"

cloudera_config=`dirname $0`
cloudera_config=`cd "$cloudera_config/../common"; pwd`
. ${cloudera_config}/cloudera-config.sh

# load the parcel environment
source_parcel_environment

# attempt to find java
locate_cdh_java_home

# simulate /etc/default/hadoop if necessary
. ${cloudera_config}/cdh-default-hadoop

echo "using $JAVA_HOME as JAVA_HOME"
echo "using $CDH_VERSION as CDH_VERSION"
echo "using $CONF_DIR as CONF_DIR"

MAIN=com.cloudera.enterprise.chive.Main

# Create the CLASSPATH for executing chive. It needs:
# - Hive
# - Hadoop (Common + MR client, any version + HDFS client).
# - Hive and Hadoop configurations.
CLASSPATH=$(ls ${MGMT_HOME}/lib/dr/chive-*.jar | head -n 1)
CLASSPATH="$CLASSPATH:$CONF_DIR/hadoop-conf"
CLASSPATH="$CLASSPATH:$CONF_DIR/hive-conf"
CLASSPATH="$CLASSPATH:$(hadoop classpath)"
CLASSPATH="$CLASSPATH:$CDH_HIVE_HOME/*"
CLASSPATH="$CLASSPATH:$CDH_HIVE_HOME/lib/*"
CLASSPATH="$CLASSPATH:${CDH_HCAT_HOME}/share/webhcat/java-client/hive-webhcat-java-client.jar"
CLASSPATH="$CLASSPATH:${CDH_HCAT_HOME}/share/hcatalog/hive-hcatalog-core.jar"

# Check if there's anything we should add to the classpath.
HIVE_ENV="$CONF_DIR/hive-conf/hive-env.sh"
if [ -f $HIVE_ENV ]; then
  . $HIVE_ENV
fi
if [ -n "$AUX_CLASSPATH" ]; then
  CLASSPATH="$CLASSPATH:$AUX_CLASSPATH"
fi

acquire_kerberos_tgt hdfs.keytab

EXTRA_ARGS=
if [ -f $CONF_DIR/target-conf/hdfs.tgt ]; then
  EXTRA_ARGS="--tgt $CONF_DIR/target-conf/hdfs.tgt"
fi

# Disable IPv6.
JAVA_OPTS="-Djava.net.preferIPv4Stack=true -Dlog4j.configuration=hadoop-conf/log4j.properties $JAVA_OPTS"

exec $JAVA_HOME/bin/java $JAVA_OPTS -cp "$CLASSPATH" $MAIN \
    -s $CONF_DIR/logs/summary.json $EXTRA_ARGS "$@"
