#! /usr/bin/env bash
#/**
# @@@ START COPYRIGHT @@@
#
#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.
#
# @@@ END COPYRIGHT @@@
# */
# 
# The wms command script.  
#
# Environment Variables:
#
#   JAVA_HOME        The java implementation to use.  Overrides JAVA_HOME.
#
#   WMS_CLASSPATH  Extra Java CLASSPATH entries.
#
#   WMS_HEAPSIZE   The maximum amount of heap to use, in MB. 
#                    Default is 1000.
#
#   WMS_LIBRARY_PATH  wms additions to JAVA_LIBRARY_PATH for adding
#                    native libaries.
#
#   WMS_OPTS       Extra Java runtime options.
#
#   WMS_CONF_DIR   Alternate conf dir. Default is ${WMS_HOME}/conf.
#
#   WMS_ROOT_LOGGER The root appender. Default is INFO,console
#
#
bin=`dirname "$0"`
bin=`cd "$bin">/dev/null; pwd`

# This will set WMS_HOME, etc.
. "$bin"/wms-config.sh

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

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

# if no args specified, show usage
if [ $# = 0 ]; then
  echo "Usage: wms <command>"
  echo "where <command> an option from one of these categories:"
  echo ""
  echo "DBA TOOLS"
  echo "  shell            run the wms shell"
  echo "  zkcli            run the ZooKeeper shell"
  echo ""
  echo "PROCESS MANAGEMENT"
  echo "  master           run a Wms master" 
  echo "  server     	   run a Wms server" 
  echo "  zookeeper        run a Zookeeper server"
  echo "  rest             run a Wms REST server" 
  echo ""
  echo "PACKAGE MANAGEMENT"
  echo "  classpath        dump Wms 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 

MVN="mvn"
if [ "$MAVEN_HOME" != "" ]; then
  MVN=${MAVEN_HOME}/bin/mvn
fi

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

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

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

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

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="${WMS_HOME}/target/cached_classpath.txt"
  if [ ! -f "${f}" ]
  then
    ${MVN} -f "${WMS_HOME}/pom.xml" dependency:build-classpath -Dmdep.outputFile="${f}" &> /dev/null
  fi
  CLASSPATH=${CLASSPATH}:`cat "${f}"`
}

add_maven_main_classes_to_classpath() {
  if [ -d "$WMS_HOME/target/classes" ]; then
    CLASSPATH=${CLASSPATH}:$WMS_HOME/target/classes
  fi
}

add_maven_test_classes_to_classpath() {
  # For developers, add wms classes to CLASSPATH
  f="$WMS_HOME/target/test-classes"
  if [ -d "${f}" ]; then
    CLASSPATH=${CLASSPATH}:${f}
  fi
}

# Add maven target directory
if $in_dev_env; then
  add_maven_deps_to_classpath
  add_maven_main_classes_to_classpath
  add_maven_test_classes_to_classpath
fi

# For releases, add wms to CLASSPATH
for f in $WMS_HOME/wms*.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 $WMS_HOME/lib/*.jar; do
  CLASSPATH=${CLASSPATH}:$f;
done

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

# default log directory & file
if [ "$WMS_LOG_DIR" = "" ]; then
  WMS_LOG_DIR="$WMS_HOME/logs"
fi
if [ "$WMS_LOGFILE" = "" ]; then
  WMS_LOGFILE='wms.log'
fi

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

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

JAVA_PLATFORM=""

if [ -d "${WMS_HOME}/build/native" -o -d "${WMS_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 "$WMS_HOME/build/native" ]; then
    JAVA_LIBRARY_PATH=$(append_path "$JAVA_LIBRARY_PATH" ${WMS_HOME}/build/native/${JAVA_PLATFORM}/lib)
  fi

  if [ -d "${WMS_HOME}/lib/native" ]; then
    JAVA_LIBRARY_PATH=$(append_path "$JAVA_LIBRARY_PATH" ${WMS_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=("shell" "zkcli")
for cmd in $client_cmds; do
	if [[ $cmd == $COMMAND ]]; then
		client=true
		break
	fi
done

if [[ $client ]]; then
	WMS_OPTS="$WMS_OPTS $CLIENT_GC_OPTS"
else
	WMS_OPTS="$WMS_OPTS $SERVER_GC_OPTS"
fi

# figure out which class to run
if [ "$COMMAND" = "zkcli" ] ; then
  # ZooKeeperMainServerArg returns '-server HOST:PORT' or empty string.
  SERVER_ARG=`"$bin"/wms --config "$WMS_CONF_DIR" org.trafodion.wms.zookeeper.ZooKeeperMainServerArg`
  CLASS="org.apache.zookeeper.ZooKeeperMain ${SERVER_ARG}"
elif [ "$COMMAND" = "master" ] ; then
  CLASS='org.trafodion.wms.master.WmsMaster'
  if [ "$1" != "stop" ] ; then
    WMS_OPTS="$WMS_OPTS $WMS_MASTER_OPTS"
  fi
elif [ "$COMMAND" = "server" ] ; then
  CLASS='org.trafodion.wms.server.WmsServer'
  if [ "$1" != "stop" ] ; then
    WMS_OPTS="$WMS_OPTS $WMS_SERVER_OPTS"
  fi
elif [ "$COMMAND" = "shell" ] ; then
  CLASS='org.trafodion.wms.client.WmsClient'
  if [ "$1" != "stop" ] ; then
    WMS_OPTS="$WMS_OPTS $WMS_CLIENT_OPTS"
  fi
elif [ "$COMMAND" = "zookeeper" ] ; then
  CLASS='org.trafodion.wms.zookeeper.WmsQuorumPeer'
  if [ "$1" != "stop" ] ; then
    WMS_OPTS="$WMS_OPTS $WMS_ZOOKEEPER_OPTS"
  fi
elif [ "$COMMAND" = "rest" ] ; then
  CLASS='org.trafodion.wms.rest.WmsRest'
  if [ "$1" != "stop" ] ; then
    WMS_OPTS="$WMS_OPTS $WMS_REST_OPTS"
  fi

elif [ "$COMMAND" = "classpath" ] ; then
  echo $CLASSPATH
  exit 0
elif [ "$COMMAND" = "version" ] ; then
  CLASS='org.trafodion.wms.util.VersionInfo'
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
WMS_OPTS="$WMS_OPTS -Dwms.log.dir=$WMS_LOG_DIR"
WMS_OPTS="$WMS_OPTS -Dwms.log.file=$WMS_LOGFILE"
WMS_OPTS="$WMS_OPTS -Dwms.home.dir=$WMS_HOME"
WMS_OPTS="$WMS_OPTS -Dwms.id.str=$WMS_IDENT_STRING"
WMS_OPTS="$WMS_OPTS -Dwms.root.logger=${WMS_ROOT_LOGGER:-INFO,console}"
if [ "x$JAVA_LIBRARY_PATH" != "x" ]; then
  WMS_OPTS="$WMS_OPTS -Djava.library.path=$JAVA_LIBRARY_PATH"
  export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$JAVA_LIBRARY_PATH"
fi

# Exec unless WMS_NOEXEC is set.
if [ "${WMS_NOEXEC}" != "" ]; then
 echo exec "$JAVA" -XX:OnOutOfMemoryError="kill -9 %p" $JAVA_HEAP_MAX $WMS_OPTS -classpath "$CLASSPATH" $CLASS "$@"
else
 exec "$JAVA" -XX:OnOutOfMemoryError="kill -9 %p" $JAVA_HEAP_MAX $WMS_OPTS -classpath "$CLASSPATH" $CLASS "$@"
fi
