#! /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 rest command script.  
#
# Environment Variables:
#
#   JAVA_HOME        The java implementation to use. Overrides JAVA_HOME.
#
#   REST_CLASSPATH  Extra Java CLASSPATH entries.
#
#   REST_HEAPSIZE   The maximum amount of heap to use, in MB. 
#                    Default is 128.
#
#   REST_LIBRARY_PATH  REST additions to JAVA_LIBRARY_PATH for adding
#                    native libaries.
#
#   REST_OPTS       Extra Java runtime options.
#
#   REST_CONF_DIR   Alternate conf dir. Default is ${REST_HOME}/conf.
#
#   REST_ROOT_LOGGER The root appender. Default is INFO,console
#
#
bin=`dirname "$0"`
bin=`cd "$bin">/dev/null; pwd`

# This will set REST_HOME, etc.
. "$bin"/rest-config.sh

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

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

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

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

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

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

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

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

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

add_maven_test_classes_to_classpath() {
  # For developers, add rest classes to CLASSPATH
  f="$REST_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 rest to CLASSPATH
for f in $REST_HOME/rest*.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 $REST_HOME/lib/*.jar; do
  CLASSPATH=${CLASSPATH}:$f;
done

# default log directory & file
if [ "$REST_LOG_DIR" = "" ]; then
  REST_LOG_DIR="$REST_HOME/logs"
fi
if [ "$REST_LOGFILE" = "" ]; then
  REST_LOGFILE='rest.log'
fi

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

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

JAVA_PLATFORM=""

#If avail, add Trafodion to the JAVA_LIBRARY_PATH
if [ "$TRAF_HOME" != "" ]; then
  if [ -d $TRAF_HOME ]; then
     export LD_PRELOAD=$JAVA_HOME/jre/lib/amd64/libjsig.so:$TRAF_HOME/export/lib$SQ_MBTYPE/libseabasesig.so;
  fi
fi

# Add user-specified CLASSPATH last
if [ "$REST_CLASSPATH" != "" ]; then
  CLASSPATH=${CLASSPATH}:${REST_CLASSPATH}
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 server_cmds=("rest")
for cmd in ${server_cmds[@]}; do
    if [[ $cmd == $COMMAND ]]; then
        server=true
        break
    fi
done

if [[ $server ]]; then
    DCS_OPTS="$REST_OPTS $SERVER_GC_OPTS"
else
    DCS_OPTS="$REST_OPTS $CLIENT_GC_OPTS"
fi

# figure out which class to run
if [ "$COMMAND" = "zkcli" ] ; then
  # ZooKeeperMainServerArg returns '-server HOST:PORT' or empty string.
  SERVER_ARG=`"$bin"/rest --config "$REST_CONF_DIR" org.trafodion.rest.zookeeper.ZooKeeperMainServerArg`
  CLASS="org.apache.zookeeper.ZooKeeperMain ${SERVER_ARG}"
elif [ "$COMMAND" = "rest" ] ; then
  CLASS='org.trafodion.rest.TrafodionRest'
  if [ "$1" != "stop" ] ; then
    REST_OPTS="$REST_OPTS $REST_REST_OPTS"
  fi

elif [ "$COMMAND" = "classpath" ] ; then
  echo $CLASSPATH
  exit 0
elif [ "$COMMAND" = "version" ] ; then
  CLASS='org.trafodion.rest.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
REST_OPTS="$REST_OPTS -Drest.log.dir=$REST_LOG_DIR"
REST_OPTS="$REST_OPTS -Drest.log.file=$REST_LOGFILE"
REST_OPTS="$REST_OPTS -Drest.home.dir=$REST_HOME"
REST_OPTS="$REST_OPTS -Drest.id.str=$REST_IDENT_STRING"
REST_OPTS="$REST_OPTS -Drest.root.logger=${REST_ROOT_LOGGER:-INFO,console}"

if [ "x$JAVA_LIBRARY_PATH" != "x" ]; then
  REST_OPTS="$REST_OPTS -Djava.library.path=$JAVA_LIBRARY_PATH"
  export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$JAVA_LIBRARY_PATH"
fi
REST_OPTS="$REST_OPTS -Drest.user.program.home=$REST_USER_PROGRAM_HOME"
REST_OPTS="$REST_OPTS -Drest.conf.dir=$REST_CONF_DIR"
REST_OPTS="$REST_OPTS -Drest.trafodion.home=$TRAF_HOME"

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