#!/bin/bash

# Copyright (c) 2013 Cloudera, Inc. All rights reserved.
#
# Runs the HBase snapshot set management tool.

# 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

set_hbase_classpath

export HBASE_HOME=$CDH_HBASE_HOME

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

MAIN="com.cloudera.enterprise.bdr.snapshots.hbase.Main"

locate_hbase_script

MR_CONF_DIR=${CONF_DIR}/mr-conf

if [ "MAPREDUCE" = "$MAPREDUCE_SERVICE_TYPE" ]; then
  HADOOP_HOME=${CDH_MR1_HOME}
  echo "using $CDH_MR1_HOME as CDH_MR1_HOME"
  perl -pi -e "s#{{CDH_MR1_HOME}}#$CDH_MR1_HOME#g" $MR_CONF_DIR/*
elif [ "YARN" = "$MAPREDUCE_SERVICE_TYPE" ]; then
  HADOOP_HOME=${CDH_HADOOP_HOME}
  echo "using $CDH_MR2_HOME as CDH_MR2_HOME"
  perl -pi -e "s#{{CDH_MR2_HOME}}#$CDH_MR2_HOME#g" $MR_CONF_DIR/*
elif [ "" = "$MAPREDUCE_SERVICE_TYPE" ]; then
  echo "No MR service type"
else
  echo "Invalid value for MAPREDUCE_SERVICE_TYPE: $MAPREDUCE_SERVICE_TYPE"
  exit 1
fi

# Create the CLASSPATH for executing snapshot-hbase.
# - snapshots-common
# - hbase-remote-snapshot-utils
# - cloudera-manager-api
# - several apache common libs
# - HBase configuration
# - optional MR configuration
# - HBase
# - Hadoop common
CLASSPATH=$(ls ${MGMT_HOME}/lib/dr/snapshot-hbase-*.jar | head -n 1)
COMMONLIB=$(ls ${MGMT_HOME}/lib/dr/snapshots-common-*.jar | head -n 1)
REMOTEUTILSLIB=$(ls ${MGMT_HOME}/lib/dr/hbase-remote-snapshot-utils-*.jar | head -n 1)
CLASSPATH="$CLASSPATH:$COMMONLIB:$REMOTEUTILSLIB"
CLASSPATH="$CLASSPATH:${MGMT_HOME}/lib/*"
CLASSPATH="$CLASSPATH:$MR_CONF_DIR:$CONF_DIR/hbase-conf"
CLASSPATH="$CLASSPATH:$(${HBASE_BIN} classpath)"

# Add hadoop native libraries to java library path
# Disable IPv6.
set_hadoop_native_library_path
export JAVA_OPTS="$JAVA_OPTS -Djava.net.preferIPv4Stack=true -Djava.library.path=$JAVA_LIBRARY_PATH"

acquire_kerberos_tgt hbase.keytab

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