#!/usr/bin/env bash

# CONTROLLING STARTUP:
#
# Use DataCube -help to see available command-line options. In addition
# to passing command-line options, this script looks for an include
# file named DataCube.config to set environment variables.
#
# Note: This is particularly handy for running multiple instances on a 
# single installation, or for quick tests.
#

SCRIPT_PATH="$0"
verbose=true
THIS_OS=`uname -s`
JETTY_START_JAR="jetty-start.jar"
CONFIG_FILENAME="CvDataCube.config"

# for now, we don't support running this script from cygwin due to problems
# like not having lsof, ps auxww, curl, and awkward directory handling
if [ "${THIS_OS:0:6}" == "CYGWIN" ]; then
  echo -e "This script does not support cygwin due to severe limitations and lack of adherence\nto BASH standards, such as lack of lsof, curl, and ps options.\n\nPlease use the native solr.cmd script on Windows!"
  exit 1
fi

# Resolve symlinks to this script
while [ -h "$SCRIPT_PATH" ] ; do
  ls=`ls -ld "$SCRIPT_PATH"`
  # Drop everything prior to ->
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    SCRIPT_PATH="$link"
  else
    SCRIPT_PATH=`dirname "$SCRIPT_PATH"`/"$link"
  fi
done

BASE_PATH=`dirname "$SCRIPT_PATH"`/..
BASE_PATH=`cd "$BASE_PATH"; pwd`

# Get all the configuration for starting
. "`dirname "$0"`/$CONFIG_FILENAME"

if [ -n "$SOLR_JAVA_HOME" ]; then
  JAVA="$SOLR_JAVA_HOME/bin/java"
elif [ -n "$JAVA_HOME" ]; then
  for java in "$JAVA_HOME"/bin/amd64/java "$JAVA_HOME"/bin/java; do
    if [ -x "$java" ]; then
      JAVA="$java"
      break
    fi
  done
  if [ -z "$JAVA" ]; then
    echo >&2 "The currently defined JAVA_HOME ($JAVA_HOME) refers"
    echo >&2 "to a location where Java could not be found.  Aborting."
    echo >&2 "Either fix the JAVA_HOME variable or remove it from the"
    echo >&2 "environment so that the system PATH will be searched."
    exit 1
  fi
else
  JAVA=java
fi

# test that Java exists and is executable on this server
"$JAVA" -version >/dev/null 2>&1 || {
  echo >&2 "Java not found, or an error was encountered when running java."
  echo >&2 "A working Java 7 or later is required to run Solr!"
  echo >&2 "Please install Java or fix JAVA_HOME before running this script."
  echo >&2 "Command that we tried: '${JAVA} -version'"
  echo >&2 "Active Path:"
  echo >&2 "${PATH}"
  exit 1
}

# Select HTTP OR HTTPS related configurations
SOLR_URL_SCHEME=http
SOLR_JETTY_CONFIG=()
SOLR_SSL_OPTS=""
if [ -n "$SOLR_SSL_KEY_STORE" ]; then
  SOLR_JETTY_CONFIG+=("--module=https")
  SOLR_URL_SCHEME=https
  SOLR_SSL_OPTS=" -Dsolr.jetty.keystore=$SOLR_SSL_KEY_STORE \
    -Dsolr.jetty.keystore.password=$SOLR_SSL_KEY_STORE_PASSWORD \
    -Dsolr.jetty.truststore=$SOLR_SSL_TRUST_STORE \
    -Dsolr.jetty.truststore.password=$SOLR_SSL_TRUST_STORE_PASSWORD \
    -Dsolr.jetty.ssl.needClientAuth=$SOLR_SSL_NEED_CLIENT_AUTH \
    -Dsolr.jetty.ssl.wantClientAuth=$SOLR_SSL_WANT_CLIENT_AUTH"
  if [ -n "$SOLR_SSL_CLIENT_KEY_STORE" ]; then
    SOLR_SSL_OPTS+=" -Djavax.net.ssl.keyStore=$SOLR_SSL_CLIENT_KEY_STORE \
      -Djavax.net.ssl.keyStorePassword=$SOLR_SSL_CLIENT_KEY_STORE_PASSWORD \
      -Djavax.net.ssl.trustStore=$SOLR_SSL_CLIENT_TRUST_STORE \
      -Djavax.net.ssl.trustStorePassword=$SOLR_SSL_CLIENT_TRUST_STORE_PASSWORD"
  else
    SOLR_SSL_OPTS+=" -Djavax.net.ssl.keyStore=$SOLR_SSL_KEY_STORE \
      -Djavax.net.ssl.keyStorePassword=$SOLR_SSL_KEY_STORE_PASSWORD \
      -Djavax.net.ssl.trustStore=$SOLR_SSL_TRUST_STORE \
      -Djavax.net.ssl.trustStorePassword=$SOLR_SSL_TRUST_STORE_PASSWORD"
  fi
else
  SOLR_JETTY_CONFIG+=("--module=http")
fi

# Authentication options
if [ "$SOLR_AUTHENTICATION_CLIENT_CONFIGURER" != "" ]; then
  AUTHC_CLIENT_CONFIGURER_ARG="-Dsolr.authentication.httpclient.configurer=$SOLR_AUTHENTICATION_CLIENT_CONFIGURER"
fi
AUTHC_OPTS="$AUTHC_CLIENT_CONFIGURER_ARG $SOLR_AUTHENTICATION_OPTS"

# Set the SOLR_TOOL_HOST variable for use when connecting to a running Solr instance
if [ "$SOLR_HOST" != "" ]; then
  SOLR_TOOL_HOST="$SOLR_HOST"
else
  SOLR_TOOL_HOST="localhost"
fi

# Sets standard logs
if [ ! -z "$SERVICE_STDOUT" ]; then
  if [ "$SERVICE_STDOUT" == "auto" ]; then
    SOLR_STDOUT_FILE="$SERVICE_LOGS_DIR/$SERVICE_NAME-stdout.log"
  else
    SOLR_STDOUT_FILE="$SERVICE_STDOUT"
  fi
else
  SOLR_STDOUT_FILE="/dev/null"
fi

if [ ! -z "$SERVICE_STDERR" ]; then
  if [ "$SERVICE_STDERR" == "auto" ]; then
    SOLR_STDERR_FILE="$SERVICE_LOGS_DIR/$SERVICE_NAME-stderr.log"
  else
    SOLR_STDERR_FILE="$SERVICE_STDERR"
  fi
else
  SOLR_STDERR_FILE="/dev/null"
fi

function print_usage() {
  CMD="$1"
  ERROR_MSG="$2"
    
  if [ "$ERROR_MSG" != "" ]; then
    echo -e "\nERROR: $ERROR_MSG\n"
  fi
  
  if [ -z "$CMD" ]; then
    echo ""
    echo "Usage: DataCube COMMAND OPTIONS"
    echo "       where COMMAND is one of: start, stop, update"
    echo ""
  fi
} # end print_usage

# used to show the script is still alive when waiting on work to complete
function spinner() {
  local pid=$1
  local delay=0.5
  local spinstr='|/-\'
  while [ "$(ps aux | awk '{print $2}' | grep -w $pid)" ]; do
      local temp=${spinstr#?}
      printf " [%c]  " "$spinstr"
      local spinstr=$temp${spinstr%"$temp"}
      sleep $delay
      printf "\b\b\b\b\b\b"
  done
  printf "    \b\b\b\b"
}

# extract the value of the -Djetty.port parameter from a running Solr process 
function jetty_port() {
  SOLR_PID="$1"
  SOLR_PROC=`ps auxww | grep -w $SOLR_PID | grep $STOP_KEY | grep jetty.port`
  IFS=' ' read -a proc_args <<< "$SOLR_PROC"
  for arg in "${proc_args[@]}"
    do
      IFS='=' read -a pair <<< "$arg"
      if [ "${pair[0]}" == "-Djetty.port" ]; then
        local jetty_port="${pair[1]}"
        break
      fi
    done    
  echo "$jetty_port"
} # end jetty_port func

# Launches Solr in background
function start_solr() {
  SOLR_ADDL_ARGS="$1"
  stop_port="$STOP_PORT"
  GC_TUNE=($GC_TUNE)
  # deal with Java version specific GC and other flags
  if [ "${JAVA_VERSION:0:3}" == "1.7" ]; then
    # Specific Java version hacking
    GC_TUNE+=('-XX:CMSFullGCsBeforeCompaction=1' '-XX:CMSTriggerPermRatio=80')
    if [ "$JAVA_VENDOR" != "IBM J9" ]; then
      JAVA_MINOR_VERSION=${JAVA_VERSION:(-2)}
      if [[ $JAVA_MINOR_VERSION -ge 40 && $JAVA_MINOR_VERSION -le 51 ]]; then
        GC_TUNE+=('-XX:-UseSuperWord')
        echo -e "\nWARNING: Java version $JAVA_VERSION has known bugs with Lucene and requires the -XX:-UseSuperWord flag. Please consider upgrading your JVM.\n"
      fi
    fi
  fi

  # If SSL-related system props are set, add them to SOLR_OPTS
  if [ -n "$SOLR_SSL_OPTS" ]; then
    # If using SSL and solr.jetty.https.port not set explicitly, use the jetty.port
    SSL_PORT_PROP="-Dsolr.jetty.https.port=$SOLR_PORT"
    SOLR_OPTS+=($SOLR_SSL_OPTS "$SSL_PORT_PROP")
  fi

  # If authentication system props are set, add them to SOLR_OPTS
  if [ -n "$AUTHC_OPTS" ]; then
    SOLR_OPTS+=($AUTHC_OPTS)
  fi

  if $verbose ; then
    echo -e "\nStarting Solr using the following settings:"
    echo -e "    JAVA            = $JAVA"
    echo -e "    SOLR_SERVER_DIR = $SOLR_SERVER_DIR"
    echo -e "    SOLR_HOME       = $SOLR_HOME"
    echo -e "    SOLR_HOST       = $SOLR_HOST"
    echo -e "    SOLR_PORT       = $SOLR_PORT"
    echo -e "    STOP_PORT       = $STOP_PORT"
    echo -e "    JAVA_MEM_OPTS   = ${JAVA_MEM_OPTS[@]}"
    echo -e "    GC_TUNE         = ${GC_TUNE[@]}"
    echo -e "    GC_LOG_OPTS     = ${GC_LOG_OPTS[@]}"
    echo -e "    SOLR_TIMEZONE   = $SOLR_TIMEZONE"

    if [ "$SOLR_MODE" == "solrcloud" ]; then
      echo -e "    CLOUD_MODE_OPTS = ${CLOUD_MODE_OPTS[@]}"
    fi

    if [ "$SOLR_OPTS" != "" ]; then
      echo -e "    SOLR_OPTS        = ${SOLR_OPTS[@]}"
    fi

    if [ "$SOLR_ADDL_ARGS" != "" ]; then
      echo -e "    SOLR_ADDL_ARGS   = $SOLR_ADDL_ARGS"
    fi

    if [ "$ENABLE_REMOTE_JMX_OPTS" == "true" ]; then
      echo -e "    RMI_PORT        = $RMI_PORT"
      echo -e "    REMOTE_JMX_OPTS = ${REMOTE_JMX_OPTS[@]}"
    fi

    if [ "$ENABLE_REMOTE_DEBUG_OPTS" == "true" ]; then
      echo -e "    DEBUG_PORT      = $DEBUG_PORT"
      echo -e "    REMOTE_DEBUG_OPTS = ${REMOTE_DEBUG_OPTS[@]}"
    fi
    echo -e "\n"
  fi
    
  # need to launch solr from the server dir
  cd "$SOLR_SERVER_DIR"
  
  if [ ! -e "$SOLR_SERVER_DIR/$JETTY_START_JAR" ]; then
    echo -e "\nERROR: $JETTY_START_JAR file not found in $SOLR_SERVER_DIR!\n"
    exit 1
  fi

  SOLR_START_OPTS=('-server' '-Xss256k' "${JAVA_MEM_OPTS[@]}" "${GC_TUNE[@]}" "${GC_LOG_OPTS[@]}" \
    "${REMOTE_JMX_OPTS[@]}" "${REMOTE_DEBUG_OPTS[@]}" "${CLOUD_MODE_OPTS[@]}" \
    "-Djetty.port=$SOLR_PORT" "-DSTOP.PORT=$stop_port" "-DSTOP.KEY=$STOP_KEY" \
    "${SOLR_HOST_ARG[@]}" "-Duser.timezone=$SOLR_TIMEZONE" \
    "-Djetty.home=$SOLR_SERVER_DIR" "-Dsolr.solr.home=$SOLR_HOME" "-Dsolr.install.dir=$BASE_PATH" \
    "${LOG4J_CONFIG[@]}" "${SOLR_OPTS[@]}")

  if [ "$SOLR_MODE" == "solrcloud" ]; then
    IN_CLOUD_MODE=" in SolrCloud mode"
  fi

  if [ "$RESTART_ON_OUT_OF_MEMORY_ERROR" == "true" ]; then
    SOLR_OUT_OF_MEMORY="-XX:OnOutOfMemoryError=oom_handler $SOLR_SERVER_DIR $SOLR_PORT $STOP_PORT $STOP_KEY $SOLR_PID $OMM_LOG_FILE"
  fi

  mkdir -p "$SOLR_LOGS_DIR"
  mkdir -p "$SERVICE_LOGS_DIR"

  # run Solr in the background
  nohup "$JAVA" "${SOLR_START_OPTS[@]}" $SOLR_ADDL_ARGS -cp $JETTY_START_JAR:$DATACUBE_BASE_PATH/app/sharedLib/*:$SOLR_SERVER_DIR/* org.eclipse.jetty.start.Main \
    "$SOLR_OUT_OF_MEMORY $SOLR_PORT $SERVICE_LOGS_DIR" "${SOLR_JETTY_CONFIG[@]}" \
    1> "$SOLR_STDOUT_FILE" 2> "$SOLR_STDERR_FILE" &

  SCRIPTPATH=`pwd`
  SCPATH="$SCRIPTPATH/../../../../../Base/svc_ctrl"
  # no lsof on cygwin though
  if hash lsof 2>/dev/null ; then  # hash returns true if lsof is on the path
    echo -n "Waiting up to 30 seconds to see Solr running on port $SOLR_PORT"
    # Launch in a subshell to show the spinner
    (loops=0
    while true
    do
      running=`lsof -PniTCP:$SOLR_PORT -sTCP:LISTEN`
      if [ -z "$running" ]; then
        if [ $loops -lt 60 ]; then
          sleep 5
          loops=$[$loops+1]
        else
          echo -e "Still not seeing Solr listening on $SOLR_PORT after 300 seconds!"
          exit # subshell!
        fi
      else
        SOLR_PID=`ps auxww | grep $STOP_KEY | grep -w $SOLR_PORT | grep -v grep | awk '{print $2}' | sort -r`
        echo -e "\nStarted Solr server on port $SOLR_PORT (pid=$SOLR_PID). Happy searching!\n"
        pushd `dirname $0` > /dev/null
        popd > /dev/null
        $SCPATH -focus $INSTANCE_NAME -checkin DataCube  $SOLR_PID
        exit # subshell!
      fi
    done) &
    spinner $!
  else
    echo -e "NOTE: Please install lsof as this script needs it to determine if Solr is listening on port $SOLR_PORT."
    sleep 10
    SOLR_PID=`ps auxww | grep $STOP_KEY | grep -w $SOLR_PORT | grep -v grep | awk '{print $2}' | sort -r`
    echo -e "\nStarted Solr server on port $SOLR_PORT (pid=$SOLR_PID). Happy searching!\n"
	$SCPATH -focus $INSTANCE_NAME -checkin DataCube  $SOLR_PID
    return;
  fi
} # end start_solr

# tries to gracefully stop Solr using the Jetty 
# stop command and if that fails, then uses kill -9
function stop_solr() {
  DIR="$1"
  solr_start_port="$2"
  solr_stop_port="$3"
  solr_stop_key="$4"
  solr_start_pid="$5"

  if [ "$solr_start_pid" != "" ]; then
    echo -e "Sending stop command to Solr running on port $solr_start_port..."
    nohup "$JAVA" $SOLR_SSL_OPTS $AUTHC_OPTS -jar "$DIR/$JETTY_START_JAR" "STOP.PORT=$solr_stop_port" \
    "STOP.KEY=$solr_stop_key" --stop "$SOLR_STD_LOGS" \
    1> "$SOLR_STDOUT_FILE" 2> "$SOLR_STDERR_FILE" &
  else
    echo -e "No Solr nodes found to stop."
    exit 0
  fi

  # no lsof on cygwin though
  if hash lsof 2>/dev/null ; then  # hash returns true if lsof is on the path
    echo -n "Waiting up to 30 seconds to allow Jetty process $solr_start_pid to stop gracefully."
    # Launch in a subshell to show the spinner
    (loops=0
    while true
    do
      running=`lsof -PniTCP:$solr_start_port -sTCP:LISTEN`
      if [ -z "$running" ]; then
        echo -e "\nSolr server Stopped on port $solr_start_port (pid=$solr_start_pid)\n"
        exit # subshell!
      else
        if [ $loops -lt 60 ]; then
          sleep 5
          loops=$[$loops+1]
        else
          echo -e "Still seeing Solr listening on $solr_start_port after 300 seconds!"
          exit # subshell!
        fi
      fi
    done) &
    spinner $!
  else
    echo -e "NOTE: Please install lsof as this script needs it to determine if Solr is listening on port $solr_start_port."
    sleep 10
  fi

  # Check if the process is down, else kill it! 
  CHECK_PID=`ps auxww | awk '{print $2}' | grep -w $solr_start_pid | sort -r | tr -d ' '`
  if [ "$CHECK_PID" != "" ]; then
    echo -e "Solr process $solr_start_pid is still running; forcefully killing it now."
    kill -9 $solr_start_pid
    echo "Killed process $solr_start_pid"
    sleep 1
  fi
} # end stop_solr

# Restarts Solr using stop and start commands
function restart_solr() {
  DIR="$1"
  solr_start_port="$2"
  solr_stop_port="$3"
  solr_stop_key="$4"
  solr_start_pid="$5"

  echo "Running OOM killer script for process $solr_start_pid for Solr on port $solr_start_port"
  stop_solr "$DIR" "$solr_start_port" "$solr_stop_port" "$solr_stop_key" "$solr_start_pid"
  start_solr "$ADDITIONAL_CMD_OPTS"
}

#Get canonical time zone tp handle daylight saving.
function getTimeZone() {
if filename=$(readlink /etc/localtime); then
    # /etc/localtime is a symlink as expected
    timezone=${filename#*zoneinfo/}
    if [[ $timezone = "$filename" || ! $timezone =~ ^[^/]+/[^/]+$ ]]; then
        # not pointing to expected location or not Region/City
        echo "$filename points to an unexpected location"
        SOLR_TIMEZONE=`date +%Z`
    else
        SOLR_TIMEZONE =  $timezone 
    fi
else  # compare files by contents
    SOLR_TIMEZONE =`find /usr/share/zoneinfo -type f ! -regex ".*/Etc/.*" -exec cmp -s {} /etc/localtime \; -print | sed -e 's@.*/zoneinfo/@@' | head -n1`
fi
}

# Restarts Solr using stop and start commands
function oom_handler() {
  DIR="$1"
  solr_start_port="$2"
  solr_stop_port="$3"
  solr_stop_key="$4"
  solr_start_pid="$5"
  solr_restart_log="$6"
  
  if [ -z "$solr_restart_log" ]; then
    solr_restart_log="OOM"
  fi

  NOW=$(date +"%F_%H_%M_%S")
  (
    echo "Running OOM killer script for process $solr_start_pid for Solr on port $solr_start_port"
    restart_solr "$DIR" "$solr_start_port" "$solr_stop_port" "$solr_stop_key" "$solr_start_pid"
  ) | tee $SERVICE_LOGS_DIR/$solr_restart_log-$SOLR_PORT-$NOW.log
}

if [ $# -gt 0 ]; then
  SCRIPT_CMD=`echo $1 | awk '{print tolower($0)}'`
  shift
else
  # no args - just show usage and exit
  #print_usage ""
  #exit
  SCRIPT_CMD="start"  
fi

# verify the command given is supported
if [ "$SCRIPT_CMD" != "stop" ] && [ "$SCRIPT_CMD" != "start" ] && [ "$SCRIPT_CMD" != "restart" ] && [ "$SCRIPT_CMD" != "update" ]; then
  print_usage "" "$SCRIPT_CMD is not a valid command!"
  exit 1
fi

SOLR_OPTS=($SOLR_OPTS)

if [ -z "$SOLR_SERVER_DIR" ]; then
  SOLR_SERVER_DIR="$DEFAULT_SERVER_DIR"
fi

if [ ! -e "$SOLR_SERVER_DIR" ]; then
  echo -e "\nSolr server directory $SOLR_SERVER_DIR not found!\n"
  exit 1
fi

############# start/stop logic below here ################
if $verbose ; then
  echo "Using Solr root directory: $BASE_PATH"
  echo "Using Java: $JAVA"
  "$JAVA" -version
fi

if [ "$SOLR_HOST" != "" ]; then
  SOLR_HOST_ARG=("-Dhost=$SOLR_HOST")
else
  SOLR_HOST_ARG=()
fi

if [ -z "$STOP_KEY" ]; then
  STOP_KEY='solrrocks'
fi

# stop all if no port specified
if [[ "$SCRIPT_CMD" == "stop" && -z "$SOLR_PORT" ]]; then
  # not stopping all and don't have a port, but if we can find the pid file for the default port, then use that
  none_stopped=true
  CHECK_PID=`ps auxww | awk '{print $2}' | grep -w $PID | sort -r | tr -d ' '`
  if [ "$CHECK_PID" != "" ]; then
    port=`jetty_port "$CHECK_PID"`
    if [ "$port" != "" ]; then
      stop_solr "$SOLR_SERVER_DIR" "$port" "$STOP_PORT" "$STOP_KEY" "$CHECK_PID"
      none_stopped=false
    fi
  fi

  if $none_stopped; then
    echo -e "\nNo Solr nodes found to stop.\n"
    exit 1
  fi
  exit $?
fi

if [ -z "$SOLR_PORT" ]; then
  SOLR_PORT=8983
fi

if [ -z "$STOP_PORT" ]; then
  STOP_PORT=`expr $SOLR_PORT - 1000`
fi

if [[ "$SCRIPT_CMD" == "start" ]]; then
  if [ -z "$SOLR_PID" ]; then
    # not found using the pid file ... but use ps to ensure not found
    SOLR_PID=`ps auxww | grep $STOP_KEY | grep -w $SOLR_PORT | grep -v grep | awk '{print $2}' | sort -r`
  fi

  if [ "$SOLR_PID" != "" ]; then
    echo -e "\nPort $SOLR_PORT is already being used by another process (pid: $SOLR_PID).\n"
    exit 1
  fi
else
  # see if Solr is already running
  if [ -z "$SOLR_PID" ]; then
    # not found using the pid file ... but use ps to ensure not found
    SOLR_PID=`ps auxww | grep $STOP_KEY | grep -w $SOLR_PORT | grep -v grep | awk '{print $2}' | sort -r`
  fi
  if [ "$SOLR_PID" != "" ]; then
    stop_solr "$SOLR_SERVER_DIR" "$SOLR_PORT" "$STOP_PORT" "$STOP_KEY" "$SOLR_PID"
  else
    if [ "$SCRIPT_CMD" == "stop" ]; then
      echo -e "No process found for Solr node running on port $SOLR_PORT"
      exit 1
    fi
  fi
fi

if [ -z "$SOLR_HOME" ]; then
  SOLR_HOME="$SOLR_SERVER_DIR/solr"
else
  if [[ $SOLR_HOME != /* ]] && [[ -d "$SOLR_SERVER_DIR/$SOLR_HOME" ]]; then
    SOLR_HOME="$SOLR_SERVER_DIR/$SOLR_HOME"
  elif [[ $SOLR_HOME != /* ]] && [[ -d "`pwd`/$SOLR_HOME" ]]; then
    SOLR_HOME="$(pwd)/$SOLR_HOME"
  fi
fi

if [ -z "$SOLR_LOGS_DIR" ]; then
  SOLR_LOGS_DIR="$SOLR_SERVER_DIR/logs"
fi

if [ -z "$SERVICE_LOGS_DIR" ]; then
  SERVICE_LOGS_DIR="$SOLR_SERVER_DIR/logs"
fi

LOG4J_CONFIG=()
if [ -n "$LOG4J_PROPS" ]; then
  LOG4J_CONFIG+=("-Dlog4j.configuration=file:$LOG4J_PROPS")
fi

if [ "$SCRIPT_CMD" == "stop" ]; then
  # already stopped, script is done.
  exit 0
fi

# NOTE: If the script gets to here, then it is starting up a Solr node.

if [ ! -e "$SOLR_HOME" ]; then
  echo -e "\nSolr home directory $SOLR_HOME not found!\n"
  exit 1
fi

java_ver_out=`echo "$("$JAVA" -version 2>&1)"`
JAVA_VERSION=`echo $java_ver_out | grep "java version" | awk '{ print substr($3, 2, length($3)-2); }'`
JAVA_VENDOR="Oracle"
if [ "`echo $java_ver_out | grep -i "IBM J9"`" != "" ]; then
  JAVA_VENDOR="IBM J9"
fi

# If ZK_HOST is defined, the assume SolrCloud mode
if [[ -n "$ZK_HOST" ]]; then
  SOLR_MODE="solrcloud"
fi

if [ "$SOLR_MODE" == 'solrcloud' ]; then
  if [ -z "$ZK_CLIENT_TIMEOUT" ]; then
    ZK_CLIENT_TIMEOUT="15000"
  fi
  
  CLOUD_MODE_OPTS=("-DzkClientTimeout=$ZK_CLIENT_TIMEOUT")
  
  if [ "$ZK_HOST" != "" ]; then
    CLOUD_MODE_OPTS+=("-DzkHost=$ZK_HOST")
  else
    if $verbose ; then
      echo "Configuring SolrCloud to launch an embedded ZooKeeper using -DzkRun"
    fi

    CLOUD_MODE_OPTS+=('-DzkRun')
  fi
else
  if [ ! -e "$SOLR_HOME/solr.xml" ]; then
    echo -e "\nSolr home directory $SOLR_HOME must contain a solr.xml file!\n"
    exit 1
  fi
fi

# These are useful for attaching remote profilers like VisualVM/JConsole
if [ "$ENABLE_REMOTE_JMX_OPTS" == "true" ]; then
  if [ -z "$RMI_PORT" ]; then
    RMI_PORT="1$SOLR_PORT"
  fi
  REMOTE_JMX_OPTS=('-Dcom.sun.management.jmxremote' \
    '-Dcom.sun.management.jmxremote.local.only=false' \
    '-Dcom.sun.management.jmxremote.ssl=false' \
    '-Dcom.sun.management.jmxremote.authenticate=false' \
    "-Dcom.sun.management.jmxremote.port=$RMI_PORT" \
    "-Dcom.sun.management.jmxremote.rmi.port=$RMI_PORT")

  # if the host is set, then set that as the rmi server hostname
  if [ "$SOLR_HOST" != "" ]; then
    REMOTE_JMX_OPTS+=("-Djava.rmi.server.hostname=$SOLR_HOST")
  fi
else
  REMOTE_JMX_OPTS=()
fi

# These are useful for attaching remote debugging
if [ "$ENABLE_REMOTE_DEBUG_OPTS" == "true" ]; then
  if [ -z "$DEBUG_PORT" ]; then
    DEBUG_PORT="9999"
  fi
  REMOTE_DEBUG_OPTS=("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:$DEBUG_PORT")
else
  REMOTE_DEBUG_OPTS=()
fi

# This enable GC logging
if [ "$ENABLE_GC_LOG_OPTS" == "true" ]; then
  GC_LOG_OPTS=("-Xlog:gc*=info,heap*=info,gc+age=debug,safepoint:file=\"${dEVLOGDIR}/Datacube_gc-%t.log\":time,uptime:filecount=25,filesize=5M")
else
  GC_LOG_OPTS=()
fi

JAVA_MEM_OPTS=()
if [ -z "$SOLR_HEAP" ] && [ -n "$SOLR_JAVA_MEM" ]; then
  JAVA_MEM_OPTS=($SOLR_JAVA_MEM)
else
  SOLR_HEAP="${SOLR_HEAP:-512m}"
  JAVA_MEM_OPTS=("-Xms$SOLR_HEAP" "-Xmx$SOLR_HEAP")
fi

if [ -z "$SOLR_TIMEZONE" ]; then
  getTimeZone
fi

# Set Application Options, if any
if [ ! -z "$APPLICATION_OPTS" ]; then
  ADDITIONAL_CMD_OPTS="$ADDITIONAL_CMD_OPTS $APPLICATION_OPTS"
fi

start_solr "$ADDITIONAL_CMD_OPTS"

exit $?

