#!/usr/pkg/bin/bash

set -e -o pipefail

CDPATH=""

SCRIPT="$0"

# SCRIPT might be an arbitrarily deep series of symbolic links; loop until we
# have the concrete path
while [ -h "$SCRIPT" ] ; do
  ls=`ls -ld "$SCRIPT"`
  # Drop everything prior to ->
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    SCRIPT="$link"
  else
    SCRIPT=`dirname "$SCRIPT"`/"$link"
  fi
done

# hardcode home dir, because we can
ES_HOME="/usr/pkg/lib/elasticsearch"

# now set the classpath
ES_CLASSPATH="$ES_HOME/lib/*"

#set default JAVA_HOME
if [ -z "$JAVA_HOME" ]; then
  JAVA_HOME="/usr/pkg/java/openjdk8"
fi

# now set the path to java
if [ -x "$JAVA_HOME/bin/java" ]; then
  JAVA="$JAVA_HOME/bin/java"
else
  set +e
  JAVA=`which java`
  echo "warning: Falling back to java on path. This behavior is deprecated. Specify JAVA_HOME"
  set -e
fi

if [ ! -x "$JAVA" ]; then
  echo "could not find java; set JAVA_HOME" >&2
  exit 1
fi

# do not let JAVA_TOOL_OPTIONS slip in (as the JVM does by default)
if [ ! -z "$JAVA_TOOL_OPTIONS" ]; then
  echo "warning: ignoring JAVA_TOOL_OPTIONS=$JAVA_TOOL_OPTIONS"
  unset JAVA_TOOL_OPTIONS
fi

# JAVA_OPTS is not a built-in JVM mechanism but some people think it is so we
# warn them that we are not observing the value of $JAVA_OPTS
if [ ! -z "$JAVA_OPTS" ]; then
  echo -n "warning: ignoring JAVA_OPTS=$JAVA_OPTS; "
  echo "pass JVM parameters via ES_JAVA_OPTS"
fi

# check the Java version
"$JAVA" -cp "$ES_CLASSPATH" org.elasticsearch.tools.java_version_checker.JavaVersionChecker

export HOSTNAME=$HOSTNAME

if [ -z "$ES_PATH_CONF" ]; then ES_PATH_CONF="/usr/pkg/etc/elasticsearch"; fi

if [ -z "$ES_PATH_CONF" ]; then
  echo "ES_PATH_CONF must be set to the configuration path"
  exit 1
fi

# now make ES_PATH_CONF absolute
ES_PATH_CONF=`cd "$ES_PATH_CONF"; pwd`

ES_DISTRIBUTION_FLAVOR=default
ES_DISTRIBUTION_TYPE=tar

if [ -z "$ES_TMPDIR" ]; then
  ES_TMPDIR=`"$JAVA" -cp "$ES_CLASSPATH" org.elasticsearch.tools.launchers.TempDirectory`
fi
