#!/bin/bash
#
# /etc/init.d/fusionauth-search -- startup script for the FusionAuth Search Engine
#
# Written by FusionAuth <dev@fusionauth.io>
#
### BEGIN INIT INFO
# chkconfig:         2345 99 10
# Provides:          fusionauth-search
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start FusionAuth
# Description:       Start the FusionAuth Search Engine.
### END INIT INFO

set -e

#
# Set the options and such
#

export JAVA_HOME=/usr/local/fusionauth/java/current
PATH=/bin:/usr/bin:/sbin:/usr/sbin
NAME=fusionauth-search
DESC="FusionAuth Search Engine"
USER=fusionauth
LOGDIR=/usr/local/fusionauth/logs
MARKER="fusionAuthSearchEngine87AFBG16"


#
# Run all the initial checks
#

if [ `id -u` -ne 0 ]; then
  echo "You need root privileges to run this script"
  exit 1
fi

# Make sure Elasticsearch is started with system locale
if [ -r /etc/sysconfig/i18n ]; then
  . /etc/sysconfig/i18n
  export LANG
fi

# Set process configuration for Elasticsearch on Linux
if [ "$(uname -s)" = "Linux" ]; then
  max_open_files=`ulimit -n`
  if [ ${max_open_files} -lt 65536 ]; then
   ulimit -n 65536
  fi

  max_map_count=`/sbin/sysctl -n vm.max_map_count`
  if [ ${max_map_count} -lt 262144 ]; then
   sysctl -w vm.max_map_count=262144 > /dev/null
  fi
fi


#
# The main case statement
#

case "$1" in
  start)
    echo -n "Starting $DESC:    "
    if pgrep -f $MARKER > /dev/null 2>&1; then
      echo "$NAME already running"
    else
      # Create and set the owner of the log dir just in case
      if [ ! -d ${LOGDIR} ]; then
        mkdir -p ${LOGDIR}
      fi
      chown -R ${USER}:root ${LOGDIR}

      START="/usr/local/fusionauth/fusionauth-search/elasticsearch/bin/elasticsearch -d"
      su -p ${USER} -c "$START"
      sleep 5

      if pgrep -f $MARKER > /dev/null 2>&1; then
        echo "(done)"
      else
        echo "(failed)"
      fi
    fi
    ;;
  stop)
    echo -n "Stopping $DESC:    "
    if pgrep -f $MARKER > /dev/null 2>&1; then
      tries=0
      code=1
      set +e
      while [[ "$tries" < 3 && "$code" != 0 ]]; do
        kill $(pgrep -f $MARKER)
        code=$?
        tries=$((tries+1))
        sleep 2
      done
      set -e

      if ! pgrep -f $MARKER > /dev/null 2>&1; then
        echo "(done)"
      else
        echo "(failed)"
      fi
    else
      echo "(not running)"
    fi
    ;;
  restart)
    $0 stop
    $0 start
    ;;
  status)
    if pgrep -f $MARKER > /dev/null 2>&1; then
      echo "${DESC} is running with pid: $(pgrep -f $MARKER)"
    else
      echo "${DESC} is not running."
      exit 3
    fi
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|status}"
    exit 1
    ;;
esac

exit 0
