#!/bin/bash

function realpath {
  echo "$(cd "$(dirname "$1")"; pwd)"/"$(basename "$1")";
}

#---------------------------------------------------------------------------------------------------
function show_help {
  echo
  echo "Usage: $0 [OPTIONS]"
  echo
  echo "Supported options:"
  echo "  --help                   - Useful information on how to run this script"
  echo "  --enable-read-only-mode  - Switches the deployment into a read-only mode"
  echo "  --disable-read-only-mode - Turns the read-only mode off for the deployment"
  echo "  --diagnostic-report      - Generates a compressed, diagnostic log output for troubleshooting purposes."
  echo "  --reset-auth             - For standard authentication source: Resets login and password."
  echo "                             For elasticsearch-native and elasticsearch-saml authentication sources:"
  echo "                             Removes the current role mappings. All users will be granted the admin role."
  echo
}

if [ "$1" == '-h' ] || [ "$1" == '--help' ]; then
  show_help
  exit 0
fi

#---------------------------------------------------------------------------------------------------
set -eu

unset BUNDLE_APP_CONFIG
unset BUNDLE_BIN_PATH
unset BUNDLE_GEMFILE
unset BUNDLE_PATH
unset BUNDLER_VERSION
unset GEM_HOME
unset GEM_PATH
unset RUBYLIB
unset RUBYOPT

BIN_DIR=$(dirname "$0")
BIN_DIR=$(realpath "$BIN_DIR")
APP_ROOT="$(cd "$BIN_DIR/.."; pwd)"
export APP_ROOT

CONFIG_DIR="$APP_ROOT/config"
LIB_DIR="$APP_ROOT/lib"

# Need this for Filebeat config
export RAILS_ENV=togo_production

# Need this because warbler uses the default one for some reason
export BUNDLE_GEMFILE=Gemfile-Togo

# War file containing all of our code
export WAR_FILE="$APP_ROOT/lib/enterprise-search.war"

# Detect the platform
PLATFORM=$(uname -s | awk '{print tolower($0)}')
ARCH=$(uname -m)
PLATFORM_FULL="$PLATFORM-$ARCH"

# Make sure the platform is supported
if [ "$PLATFORM_FULL" != "linux-x86_64" ] && [ "$PLATFORM_FULL" != "darwin-x86_64" ]; then
  echo
  echo "Elastic Enterprise Search currently only supports OSX and Linux operating systems on 64-bit platforms."
  echo
  exit 1
fi

# Filebeat locations
export FILEBEAT_BIN="$BIN_DIR/vendor/filebeat/filebeat-$PLATFORM_FULL"
export FILEBEAT_DIR="$APP_ROOT/filebeat"

#---------------------------------------------------------------------------------------------------
# shellcheck source=../lib/require_java_version.sh
source "$LIB_DIR/require_java_version.sh"

# Load common environment settings
# shellcheck source=../config/env.sh
source "$CONFIG_DIR/env.sh"

REQUIRED_APP_SERVER_JAVA_OPTS=( $APP_SERVER_JAVA_OPTS )

if [[ "${ENTERPRISE_SEARCH_SYSTEM_TMP_DIR:-}" != "true" ]] && mkdir -p "$APP_ROOT/tmp" &> /dev/null; then
  export TMPDIR=$APP_ROOT/tmp
  REQUIRED_APP_SERVER_JAVA_OPTS+=( "-Djava.io.tmpdir=$TMPDIR" )
fi

REQUIRED_APP_SERVER_JAVA_OPTS+=( '-Djruby.cli.warning.level=NIL' '-Dwarbler.debug=true' '-Djava.awt.headless=true' '-server' )

#---------------------------------------------------------------------------------------------------
# Prepare config file
#---------------------------------------------------------------------------------------------------
if [[ -z "${ENT_SEARCH_CONFIG_PATH:-}" ]]; then
  export ENT_SEARCH_CONFIG_PATH="$CONFIG_DIR/enterprise-search.yml"
fi

if [[ "$ENT_SEARCH_CONFIG_PATH" != /* ]]; then
  export ENT_SEARCH_CONFIG_PATH="$APP_ROOT/$ENT_SEARCH_CONFIG_PATH"
fi

if [[ ! -a "$ENT_SEARCH_CONFIG_PATH" ]]; then
  echo "Cannot read ENT_SEARCH_CONFIG_PATH file because it does not exist, it's currently $ENT_SEARCH_CONFIG_PATH"
  echo
  exit 1
fi

if [[ ! -r "$ENT_SEARCH_CONFIG_PATH" ]]; then
  echo "Cannot read ENT_SEARCH_CONFIG_PATH file, it's currently $ENT_SEARCH_CONFIG_PATH"
  echo
  exit 1
fi

# Detect which components we are going to run, default to all
COMPONENT=${1:-all}
echo

#---------------------------------------------------------------------------------------------------
# Handle special commands
if [ "$COMPONENT" == "--reset-install-lock" ]     || \
   [ "$COMPONENT" == "--enable-read-only-mode" ]  || \
   [ "$COMPONENT" == "--disable-read-only-mode" ] || \
   [ "$COMPONENT" == "--reset-auth" ] || \
   [ "$COMPONENT" == "--diagnostic-report" ];
then
  ENT_SEARCH_PROCESS=script exec "$_JAVA" -jar "$WAR_FILE" -S rails runner "SharedTogo.run_script!('$COMPONENT')"
  exit 0
fi

#---------------------------------------------------------------------------------------------------
# Single-process mode
#---------------------------------------------------------------------------------------------------
if [ "$COMPONENT" == "--process" ]; then
  echo "ERROR: single-process mode has been deprecated."
  echo "bin/enterprise-search now runs worker threads, connectors and Filebeat in the background."
  show_help
  exit 1
fi

#---------------------------------------------------------------------------------------------------
# Components-based mode
#---------------------------------------------------------------------------------------------------
if [ "$COMPONENT" != 'all' ]; then
  echo "ERROR: Invalid option or a component name '$COMPONENT'!"
  show_help
  exit 1
fi

echo "Enterprise Search is starting..."

echo
ENT_SEARCH_PROCESS=app-server exec "$_JAVA" "${REQUIRED_APP_SERVER_JAVA_OPTS[@]}" -jar "$WAR_FILE" -S rails runner 'SharedTogo.start_app_server!'
