#!/bin/bash

CDPATH=""
SCRIPT="$0"

# SCRIPT may be an arbitrarily deep series of symlinks. 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

# determine elasticsearch home
ES_HOME=`dirname "$SCRIPT"`/..

# make ELASTICSEARCH_HOME absolute
ES_HOME=`cd "$ES_HOME"; pwd`


# Sets the default values for elasticsearch variables used in this script
if [ -z "$CONF_DIR" ]; then
  CONF_DIR="$ES_HOME/config"
fi

# The default env file is defined at building/packaging time.
# For a distribution package, the value is "".
ES_ENV_FILE=""

# If an include is specified with the ES_INCLUDE environment variable, use it
if [ -n "$ES_INCLUDE" ]; then
    ES_ENV_FILE="$ES_INCLUDE"
fi

# Source the environment file
if [ -n "$ES_ENV_FILE" ]; then

  # If the ES_ENV_FILE is not found, try to resolve the path
  # against the ES_HOME directory
  if [ ! -f "$ES_ENV_FILE" ]; then
      ES_ENV_FILE="$ELASTIC_HOME/$ES_ENV_FILE"
  fi

  . "$ES_ENV_FILE"
  if [ $? -ne 0 ]; then
      echo "Unable to source environment file: $ES_ENV_FILE" >&2
      exit 1
  fi
fi

# don't let JAVA_TOOL_OPTIONS slip in (e.g. crazy agents in ubuntu)
# works around https://bugs.launchpad.net/ubuntu/+source/jayatana/+bug/1441487
if [ "x$JAVA_TOOL_OPTIONS" != "x" ]; then
    echo "Warning: Ignoring JAVA_TOOL_OPTIONS=$JAVA_TOOL_OPTIONS"
    unset JAVA_TOOL_OPTIONS
fi

# CONF_FILE setting was removed
if [ ! -z "$CONF_FILE" ]; then
    echo "CONF_FILE setting is no longer supported. elasticsearch.yml must be placed in the config directory and cannot be renamed."
    exit 1
fi

if [ -x "$JAVA_HOME/bin/java" ]; then
    JAVA=$JAVA_HOME/bin/java
else
    JAVA=`which java`
fi

if [ ! -x "$JAVA" ]; then
    echo "Could not find any executable java binary. Please install java in your PATH or set JAVA_HOME"
    exit 1
fi

# full hostname passed through cut for portability on systems that do not support hostname -s
# export on separate line for shells that do not support combining definition and export
HOSTNAME=`hostname | cut -d. -f1`
export HOSTNAME

declare -a args=("$@")

if [ -e "$CONF_DIR" ]; then
  args=("${args[@]}" -Edefault.path.conf="$CONF_DIR")
fi

exec "$JAVA" $ES_JAVA_OPTS -Delasticsearch -Des.path.home="$ES_HOME" -cp "$ES_HOME/lib/*" org.elasticsearch.index.translog.TranslogToolCli "${args[@]}"
