#!/bin/bash
# /etc/init.d/eltex-ems
# debian-compatible eltex-ems startup script.
# Victor Abarenov <techsupp@eltex-co.ru>
#
### BEGIN INIT INFO
# Provides:          eltex-ems
# Required-Start:    $remote_fs $syslog $network
# Required-Stop:     $remote_fs $syslog $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start eltex-ems at boot time
# Description:       Controls eltex-ems.
### END INIT INFO

PATH=/bin:/usr/bin:/sbin:/usr/sbin

DESC="Eltex.EMS Server"
NAME=eltex-ems
SCRIPTNAME=/etc/init.d/$NAME
PIDFILE=/var/run/eltex-ems/eltex-ems.pid

# These values can be overridden in /etc/default
JAVA=/usr/bin/java
# To use all the RAM: $((`awk '/^MemTotal:/{print $2}' /proc/meminfo` / 1024))
JAVA_MAX_HEAP_MB=1024
JAVA_INIT_HEAP_MB=256
JAVA_OPTS="-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/log/eltex-ems"
GC_OPTS="-XX:+UseParallelGC -XX:MaxMetaspaceSize=512m -XX:MetaspaceSize=200m"
# fixed problems for 'new Snmp(transport)'
SNMP_OPTS="-Djava.security.egd=file:/dev/./urandom"
EMS_USER=root
ELTEX_EMS_HOME="/usr/lib/eltex-ems"
FILE_LIMIT=65535

[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# EMS server's jar file
EMS_WAR=$ELTEX_EMS_HOME/lib/ems_server.war
# JVM options
JAVA_ARGS="$JAVA_OPTS $GC_OPTS $SNMP_OPTS -Xms${JAVA_INIT_HEAP_MB}m -Xmx${JAVA_MAX_HEAP_MB}m \
        -Dmodule.home=$ELTEX_EMS_HOME -Dlogging.config=$ELTEX_EMS_HOME/conf/log4j2.xml -Dfile.encoding=UTF-8 \
        -Dspring.config.location=file:/usr/lib/eltex-ems/conf/application.yml"
MIN_JAVA_VERSION=17

# daemon and daemon args
DAEMON=/usr/bin/daemon
DAEMON_ARGS="--name=$NAME --inherit --unsafe --pidfile=$PIDFILE"

# Exit if the package is not installed
[ -x "$DAEMON" ] || (echo "daemon package not installed" && exit 0)

# load environments
if [ -r /etc/default/locale ]; then
  . /etc/default/locale
  export LANG LANGUAGE
elif [ -r /etc/environment ]; then
  . /etc/environment
  export LANG LANGUAGE
fi


# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

# Make sure we run as root, since setting the max open files through
# ulimit requires root access
if [ `id -u` -ne 0 ]; then
    echo "The $NAME init script can only be run as root"
    exit 1
fi


DISTRIB_CODENAME=
source /etc/lsb-release


get_java_version() {
    if type -p "$JAVA" &> /dev/null ; then
        for token in $("$JAVA" -version 2>&1 | grep -i "version"); do
            if [[ $token =~ \"([[:digit:]])\.([[:digit:]])\.(.*)\" ]]; then
                JAVA_VERSION=${BASH_REMATCH[2]}
                return
            elif [[ $token =~ \"([[:digit:]]+)\.([[:digit:]]+)\.(.*)\" ]]; then
                JAVA_VERSION=${BASH_REMATCH[1]}
                return
            fi
        done
    fi
    JAVA_VERSION=0
}

# EMS Gui listener port checker
check_tcp_port() {
    local service=$1
    local assigned=$2
    local default=$3

    if [ -n "$assigned" ]; then
        port=$assigned
    else
        port=$default
    fi

    count=`netstat --listen --numeric-ports | grep \:$port[[:space:]] | grep -c . `

    if [ $count -ne 0 ]; then
        echo "The selected $service port ($port) seems to be in use by another program "
        echo "Please select another port to use for $NAME"
        return 1
    fi
}

#
# Function that starts the daemon/service
#
do_start()
{
    #sleep for init starting delay (start after mysql, keepalived, etc)
    sleep 1

    # the default location is /var/run/eltex-ems/eltex-ems.pid but the parent directory needs to be created
    mkdir `dirname $PIDFILE` > /dev/null 2>&1 || true
    touch `dirname $PIDFILE`/enabled > /dev/null 2>&1 || true

    # Return
    #   0 if daemon has been started
    #   1 if daemon was already running
    #   2 if daemon could not be started
    $DAEMON $DAEMON_ARGS --running && return 1

    # Verify that the jenkins port is not already in use, winstone does not exit
    # even for BindException
    check_tcp_port "tcp" "$HTTP_PORT" "9310" || return 1

    get_java_version
    if [ $JAVA_VERSION -lt $MIN_JAVA_VERSION ]; then
        log_failure_msg "$DESC requires Java $MIN_JAVA_VERSION to start"
        return 2
    fi

    #Set open files limits but only if current limits are not enough for us
    CURRENT_LIMIT=`ulimit -n`
    if [[ $CURRENT_LIMIT -lt $FILE_LIMIT ]]; then
        ulimit -n $FILE_LIMIT
    fi

    # Add the JAVA 9 and newer specific start-up parameters required by Hazelcast
    JDK_JAVA_OPTIONS="$JDK_JAVA_OPTIONS --add-modules java.se"
    JDK_JAVA_OPTIONS="$JDK_JAVA_OPTIONS --add-exports java.base/jdk.internal.ref=ALL-UNNAMED"
    JDK_JAVA_OPTIONS="$JDK_JAVA_OPTIONS --add-opens java.base/java.lang=ALL-UNNAMED"
    JDK_JAVA_OPTIONS="$JDK_JAVA_OPTIONS --add-opens java.base/java.nio=ALL-UNNAMED"
    JDK_JAVA_OPTIONS="$JDK_JAVA_OPTIONS --add-opens java.base/sun.nio.ch=ALL-UNNAMED"
    JDK_JAVA_OPTIONS="$JDK_JAVA_OPTIONS --add-opens java.management/sun.management=ALL-UNNAMED"
    JDK_JAVA_OPTIONS="$JDK_JAVA_OPTIONS --add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED"

    # start daemon with java
    $DAEMON $DAEMON_ARGS --env "JDK_JAVA_OPTIONS=$JDK_JAVA_OPTIONS" -- $JAVA $JAVA_ARGS -jar $EMS_WAR
}


#
# Verify that all eltex-ems processes have been shutdown
# and if not, then do killall for them
# return status
# 0 - records NOT FOUND
# 1 - records FOUND
get_running()
{
    local myresult=`ps -U root --no-headers -f | egrep -e '(ems_server.war)' | egrep -e '(/usr/bin/daemon)' | egrep -v egrep |  grep -c . `
    echo "$myresult"
}

# stop process with "kill -9"
force_stop()
{
    local check_result=$(get_running)
    # '!=0' - ps found records
    if [ "$check_result" != "0" ]; then
	ps aux | grep -e '--name=eltex-ems' | grep -v grep | awk '{print $2}' | xargs -i kill -9 {}
	ps aux | grep -e 'ems_server.war' | grep -v grep | awk '{print $2}' | xargs -i kill -9 {}
    fi
}

# Get the status of the daemon process
get_daemon_status()
{
    # create directory for
    mkdir `dirname $PIDFILE` > /dev/null 2>&1 || true
    local check_result=$(get_running)

	case "$check_result" in
	0)
		if [ -f $PIDFILE ]; then
			echo "$DESC is not running, but the pidfile ($PIDFILE) still exists"
			rc=1
		else
			echo "$DESC is not running"
			rc=2
		fi
    ;;
	*)
		CurPID=$(<"$PIDFILE")
		if [ -f $PIDFILE ]; then
			echo "$DESC is running with pid $CurPID"
			rc=0
		else
			echo -n "$DESC is running"
			echo ", but the pidfile ($PIDFILE) not exists"
			echo
			rc=3
		fi
		rc=0
	;;
	esac
	return $rc
}

#
# Function that stops the daemon/service
#
do_stop()
{
    # Return
    #   0 if daemon has been stopped
    #   1 if daemon was already stopped
    #   2 if daemon could not be stopped
    #   other if a failure occurred
    local error_code=0
    local res=$(get_running)
    case "$res" in
	0)
	;;

	1|2)
	    # По этой команде на ЕМС почему-то приходит "kill -1" и ЕМС на нее не реагирует. И убивается только ниже, по "kill -9"
	    # Поэтому данный блок заменил на ниже-лежащий.
	    #if [ $DAEMON $DAEMON_ARGS --stop > /dev/null 2>&1 ]; then
		    # wait for the process to really terminate
    	#	for n in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do
        # 	    sleep 1
		#       $DAEMON $DAEMON_ARGS --running || break
		#   done
	    #fi

        # выдаем на процесс демона kill -15 -- нормальное завершение
        # демон почему-то закрывает свои задачи гораздо быстрее, чем это делает ОС.
        # Т.е. если подать на PID ЕМС  "kill -15" то в лог выложиться гораздо больше информации, чем на демон "kill -15"
	    ps aux | grep -e '--name=eltex-ems' | grep -v grep | awk '{print $2}' | xargs -i kill -15 {}
	    for i in {1..30}
	    do
		    sleep 1s
		    res=$(get_running)
		    if [ "$res" == "0" ]; then
	    	    break
		    fi
	    done

	    if [ "$res" != "0" ]; then
	        force_stop && error_code=3
	    fi
	;;

	*)
	    force_stop && error_code=3
	;;
    esac

    # Many daemons don't delete their pidfiles when they exit.
    rm -f $PIDFILE
    rm -f $(dirname ${PIDFILE})/enabled > /dev/null 2>&1
    return ${error_code}
}


# ---- выполнение методов скрипта (начало тут) ----

case "$1" in
  start)
    log_daemon_msg "Starting $DESC" "$NAME"
    do_start
    res="$?"
    case "$res" in
        0|1) log_end_msg 0 ;;
        *) log_end_msg 1 ;;
    esac
  ;;
  stop)
    log_daemon_msg "Stopping $DESC" "$NAME"
    do_stop
    res="$?"
    case "$res" in
        0|1) log_end_msg 0 ;;
        *) log_end_msg 1 ;;
    esac
  ;;
  restart|force-reload)
    #
    # If the "reload" option is implemented then remove the
    # 'force-reload' alias
    #
    log_daemon_msg "Restarting $DESC" "$NAME"
    do_stop
    res="$?"
    case "$res" in
      0|1)
        do_start
        res="$?"
        case "$res" in
          0) log_end_msg 0 ;;
          1) log_end_msg 1 ;; # Old process is still running
          *) log_end_msg 1 ;; # Failed to start
        esac
      ;;
      *)
	    log_end_msg 1
	  ;; # Failed to stop
    esac
  ;;
  status)
    get_daemon_status
  ;;
  *)
    echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
    exit 3
  ;;
esac

exit 0
