#! /usr/bin/env bash
#
#/**
# * Copyright 2013 NGDATA nv
# *
# * Based on HBase's hbase script
# * Copyright 2007 The Apache Software Foundation
# *
# * 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.
# */
# 
# The hbase-indexer command script.  Based on the hadoop command script putting
# in hbase classes, libs and configurations ahead of hadoop's.
#
# TODO: Narrow the amount of duplicated code.
#
# Environment Variables:
#
#   JAVA_HOME                   The java implementation to use. Overrides JAVA_HOME.
#
#   Extra Java CLASSPATH entries.
#
#   HBASE_INDEXER_HEAPSIZE      The maximum amount of heap to use, in MB.
#                               Default is 1000.
#
#   HBASE_INDEXER_LIBRARY_PATH  HBase additions to JAVA_LIBRARY_PATH for adding
#                               native libaries.
#
#   HBASE_INDEXER_OPTS          Extra Java runtime options.
#
#   HBASE_INDEXER_CONF_DIR      Alternate conf dir. Default is ${HBASE_INDEXER_HOME}/conf.
#
#   HBASE_INDEXER_ROOT_LOGGER   The root appender. Default is INFO,console
#

# cross-platform version of gnu 'readlink -f'
realpath=$(python -c 'import os; import sys; print os.path.realpath(sys.argv[1])' "$0")
bin=`dirname "$realpath"`
bin=`cd "$bin">/dev/null; pwd`

# This will set HBASE_INDEXER_HOME, etc.
. "$bin"/hbase-indexer-config.sh

cygwin=false
case "`uname`" in
CYGWIN*) cygwin=true;;
esac

# Detect if we are in hbase-indexer sources dir
in_dev_env=false
if [ -d "${HBASE_INDEXER_HOME}/hbase-indexer-all/target" ]; then
  in_dev_env=true
fi

# if no args specified, show usage
if [ $# = 0 ]; then
  echo "Usage: hbase-indexer <command>"
  echo "where <command> an option from one of these categories:"
  echo ""
  echo "TOOLS"
  echo "  add-indexer"
  echo "  update-indexer"
  echo "  delete-indexer"
  echo "  list-indexers"
  echo ""
  echo "PROCESS MANAGEMENT"
  echo "  server           run the HBase Indexer server node"
  echo ""
  echo "REPLICATION (EVENT PROCESSING) TOOLS"
  echo "  replication-status"
  echo "  replication-wait"
  echo ""
  echo "PACKAGE MANAGEMENT"
  echo "  classpath        dump hbase CLASSPATH"
  echo "  version          print the version"
  echo ""
  echo " or"
  echo "  CLASSNAME        run the class named CLASSNAME"
  echo "Most commands print help when invoked w/o parameters."
  exit 1
fi

# get arguments
COMMAND=$1
shift

JAVA=$JAVA_HOME/bin/java
JAVA_HEAP_MAX=-Xmx1000m 

# override default settings for this command, if applicable
if [ -f "$HBASE_INDEXER_HOME/conf/hbase-indexer-env-$COMMAND.sh" ]; then
  . "$HBASE_INDEXER_HOME/conf/hbase-indexer-env-$COMMAND.sh"
fi

# check envvars which might override default args
if [ "$HBASE_INDEXER_HEAPSIZE" != "" ]; then
  #echo "run with heapsize $HBASE_INDEXER_HEAPSIZE"
  JAVA_HEAP_MAX="-Xmx""$HBASE_INDEXER_HEAPSIZE""m"
  #echo $JAVA_HEAP_MAX
fi

# so that filenames w/ spaces are handled correctly in loops below
ORIG_IFS=$IFS
IFS=

# CLASSPATH initially contains $HBASE_INDEXER_CONF_DIR
CLASSPATH="${HBASE_INDEXER_CONF_DIR}"
CLASSPATH=${CLASSPATH}:$JAVA_HOME/lib/tools.jar

add_to_cp_if_exists() {
  if [ -d "$@" ]; then
    CLASSPATH=${CLASSPATH}:"$@"
  fi
}

# hbase-indexer: disabled webapps, we'll see later if we need this
# For releases, add hbase & webapps to CLASSPATH
# Webapps must come first else it messes up Jetty
#if [ -d "$HBASE_HOME/hbase-webapps" ]; then
#  add_to_cp_if_exists "${HBASE_HOME}"
#fi
#add if we are in a dev environment
#if [ -d "$HBASE_HOME/hbase-server/target/hbase-webapps" ]; then
#  add_to_cp_if_exists "${HBASE_HOME}/hbase-server/target"
#fi

add_maven_deps_to_classpath() {
  # Need to generate classpath from maven pom. This is costly so generate it
  # and cache it. Save the file into our target dir so a mvn clean will get
  # clean it up and force us create a new one.
  f="${HBASE_INDEXER_HOME}/hbase-indexer-all/target/cached_classpath.txt"
  if [ ! -f "${f}" ]
  then
      echo "As this is a development environment, we need ${f} to be generated from maven (command: mvn compile)"
      exit 1
  fi
  CLASSPATH=${CLASSPATH}:`cat "${f}"`
}

#Add the development env class path stuff
if $in_dev_env; then
  add_maven_deps_to_classpath
fi

# hbase-indexer: disabled this, we'll see later if we'll have multiple modules
#add the hbase-indexer jars for each module
#for f in $HBASE_HOME/hbase-jars/hbase*.jar; do
#	if [[ $f = *sources.jar ]]
#  then
#    : # Skip sources.jar
#  elif [ -f $f ]
#  then
#    CLASSPATH=${CLASSPATH}:$f;
#  fi
#done

# Add libs to CLASSPATH
for f in $HBASE_INDEXER_HOME/lib/*.jar; do
  CLASSPATH=${CLASSPATH}:$f;
done

# Add user-specified CLASSPATH last
if [ "$HBASE_INDEXER_CLASSPATH" != "" ]; then
  CLASSPATH=${CLASSPATH}:${HBASE_INDEXER_CLASSPATH}
fi

# default log directory & file
if [ "$HBASE_INDEXER_LOG_DIR" = "" ]; then
  HBASE_INDEXER_LOG_DIR="$HBASE_INDEXER_HOME/logs"
fi
if [ "$HBASE_INDEXER_LOGFILE" = "" ]; then
  HBASE_INDEXER_LOGFILE='hbase-indexer.log'
fi

# cygwin path translation
if $cygwin; then
  CLASSPATH=`cygpath -p -w "$CLASSPATH"`
  HBASE_INDEXER_HOME=`cygpath -d "$HBASE_INDEXER_HOME"`
  HBASE_INDEXER_LOG_DIR=`cygpath -d "$HBASE_INDEXER_LOG_DIR"`
fi

function append_path() {
  if [ -z "$1" ]; then
    echo $2
  else
    echo $1:$2
  fi
}

JAVA_PLATFORM=""

#If avail, add Hadoop to the CLASSPATH and to the JAVA_LIBRARY_PATH
HADOOP_IN_PATH=$(PATH="${HADOOP_HOME:-${HADOOP_PREFIX}}/bin:$PATH" which hadoop 2>/dev/null)
if [ -f ${HADOOP_IN_PATH} ]; then
  HADOOP_JAVA_LIBRARY_PATH=$(HADOOP_CLASSPATH="$CLASSPATH" ${HADOOP_IN_PATH} \
                             org.apache.hadoop.hbase.util.GetJavaProperty java.library.path 2>/dev/null)
  if [ -n "$HADOOP_JAVA_LIBRARY_PATH" ]; then
    JAVA_LIBRARY_PATH=$(append_path "${JAVA_LIBRARY_PATH}" "$HADOOP_JAVA_LIBRARY_PATH")
  fi
  CLASSPATH=$(append_path "${CLASSPATH}" `${HADOOP_IN_PATH} classpath 2>/dev/null`)
fi

# hbase-indexer: disabled this, we'll see later if this makes sense
#if [ -d "${HBASE_HOME}/build/native" -o -d "${HBASE_HOME}/lib/native" ]; then
#  if [ -z $JAVA_PLATFORM ]; then
#    JAVA_PLATFORM=`CLASSPATH=${CLASSPATH} ${JAVA} org.apache.hadoop.util.PlatformName | sed -e "s/ /_/g"`
#  fi
#  if [ -d "$HBASE_HOME/build/native" ]; then
#    JAVA_LIBRARY_PATH=$(append_path "$JAVA_LIBRARY_PATH" ${HBASE_HOME}/build/native/${JAVA_PLATFORM}/lib)
#  fi
#
#  if [ -d "${HBASE_HOME}/lib/native" ]; then
#    JAVA_LIBRARY_PATH=$(append_path "$JAVA_LIBRARY_PATH" ${HBASE_HOME}/lib/native/${JAVA_PLATFORM})
#  fi
#fi

# cygwin path translation
if $cygwin; then
  JAVA_LIBRARY_PATH=`cygpath -p "$JAVA_LIBRARY_PATH"`
fi
 
# restore ordinary behaviour
unset IFS

#Set the right GC options based on the what we are running
declare -a client_cmds=("add-indexer" "list-indexers" "update-indexer" "delete-indexer" "version" "replication-status" "replication-wait")
for cmd in ${client_cmds[@]}; do
	if [[ $cmd == $COMMAND ]]; then
		client=true
		break
	fi
done

if [[ $client ]]; then
	HBASE_INDEXER_OPTS="$HBASE_INDEXER_OPTS $CLIENT_GC_OPTS"
else
	HBASE_INDEXER_OPTS="$HBASE_INDEXER_OPTS $SERVER_GC_OPTS"
fi
HBASE_INDEXER_OPTS="$HBASE_INDEXER_OPTS -Dorg.apache.hadoop.hbase.shaded.io.netty.packagePrefix=org.apache.hadoop.hbase.shaded."

# figure out which class to run
if [ "$COMMAND" = "server" ] ; then
  CLASS='com.ngdata.hbaseindexer.Main'
elif [ "$COMMAND" = "daemon" ] ; then
  CLASS='com.ngdata.hbaseindexer.Main daemon'
elif [ "$COMMAND" = "add-indexer" ] ; then
  CLASS='com.ngdata.hbaseindexer.cli.AddIndexerCli'
elif [ "$COMMAND" = "update-indexer" ] ; then
  CLASS='com.ngdata.hbaseindexer.cli.UpdateIndexerCli'
elif [ "$COMMAND" = "delete-indexer" ] ; then
  CLASS='com.ngdata.hbaseindexer.cli.DeleteIndexerCli'
elif [ "$COMMAND" = "list-indexers" ] ; then
  CLASS='com.ngdata.hbaseindexer.cli.ListIndexersCli'
elif [ "$COMMAND" = "replication-status" ] ; then
  CLASS='com.ngdata.sep.tools.monitoring.ReplicationStatusCli'
elif [ "$COMMAND" = "replication-wait" ] ; then
  CLASS='com.ngdata.sep.tools.monitoring.ReplicationWaitCli'
elif [ "$COMMAND" = "version" ] ; then
  CLASS='com.ngdata.hbaseindexer.util.VersionInfo'
elif [ "$COMMAND" = "classpath" ] ; then
  echo $CLASSPATH
  exit 0
elif [ "$COMMAND" = "version" ] ; then
  echo "todo"
  exit 0
else
  CLASS=$COMMAND
fi

# Have JVM dump heap if we run out of memory.  Files will be 'launch directory'
# and are named like the following: java_pid21612.hprof. Apparently it doesn't
# 'cost' to have this flag enabled. Its a 1.6 flag only. See:
# http://blogs.sun.com/alanb/entry/outofmemoryerror_looks_a_bit_better
HBASE_INDEXER_OPTS="$HBASE_INDEXER_OPTS -Dhbaseindexer.log.dir=$HBASE_INDEXER_LOG_DIR"
HBASE_INDEXER_OPTS="$HBASE_INDEXER_OPTS -Dhbaseindexer.log.file=$HBASE_INDEXER_LOGFILE"
HBASE_INDEXER_OPTS="$HBASE_INDEXER_OPTS -Dhbaseindexer.home.dir=$HBASE_INDEXER_HOME"
HBASE_INDEXER_OPTS="$HBASE_INDEXER_OPTS -Dhbaseindexer.id.str=$HBASE_INDEXER_IDENT_STRING"
HBASE_INDEXER_OPTS="$HBASE_INDEXER_OPTS -Dhbaseindexer.root.logger=${HBASE_INDEXER_ROOT_LOGGER:-INFO,console}"
if [ "x$JAVA_LIBRARY_PATH" != "x" ]; then
  HBASE_INDEXER_OPTS="$HBASE_INDEXER_OPTS -Djava.library.path=$JAVA_LIBRARY_PATH"
  export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$JAVA_LIBRARY_PATH"
fi

# Exporting classpath since passing the classpath with -cp seems to choke daemon mode
export CLASSPATH
# Exec unless HBASE_INDEXER_NOEXEC is set.
if [ "${HBASE_INDEXER_NOEXEC}" != "" ]; then
  "$JAVA" -Dproc_$COMMAND {-XX:OnOutOfMemoryError="kill -9 %p" $JAVA_HEAP_MAX $HBASE_INDEXER_OPTS $CLASS "$@"
else
  exec "$JAVA" -Dproc_$COMMAND -XX:OnOutOfMemoryError="kill -9 %p" $JAVA_HEAP_MAX $HBASE_INDEXER_OPTS $CLASS "$@"
fi
