#!/bin/sh
#set -x
#
# boom_srv: Management of the BOOM Server Processes
#
#Do not change the values for BOOM_SERVER, PATH or JAVA_BIN if
#you are going to use the install script! These will be
#automatically set.
#
#To change the maximum memory the server can use, edit
#the start_server function. Set in the Java call the Parameter
#-Xmx512M to e.g. -Xmx2048M to give the process up to 2GB RAM.
#
#For manual installations without the install script
#just set the BOOM_SERVER variable to the server's installation
#directory and setup the path to include java if it is
#not already on the systems default path
#BOOM_SERVER=
#export BOOM_SERVER
#JAVA_BIN=
#PATH=${JAVA_BIN}:$PATH
#export PATH
#################


SRV_CFG_FILE="./boom_srv.cfg"

# JAVA arguments
JAVA_OPTS=
# Java path (if not default java has to be used)
JAVA_BIN=/usr/bin
# Variable to hold init system (initd, systemd etc.)
SYS_INIT=


#--- BOOM_SERVER path ---
BOOM_SERVER=/opt/boom/server
export BOOM_SERVER
echo "BOOM_SERVER=${BOOM_SERVER}"
PATH=${JAVA_BIN}:${BOOM_SERVER}:/sbin:/usr/sbin:/bin:/usr/bin:${PATH}
export PATH

# default JAVA_OPTS
JAVA_OPTS="-Xmx1048M -Dfile.encoding=UTF8"


#Variable to hold active PIDS of Server
SRV_PIDS=
#Variable to hold Program Directory
PROG_DIR=


# getdir: identify the path to the program and set
#         it as PROG_DIR
# Params: program-name and $0 from call
getdir() {
  prog="$1"
  call="$2"
  if [ -z "$prog" ]
  then
    return
  fi
  #   newdir=${0%/*}
  newdir=`echo "${call}"|sed "s/${prog}$//"`
  if [ -z "$newdir" ]
  then
    whichstr=`which ${prog}|grep -v "no ${prog}"`
    newdir=`echo "$whichstr"|sed "s/${prog}$//"`
    if [ -z "$newdir" ]
    then
      return
    fi
  fi
  if [ -d "$newdir" ]
  then
    PROG_DIR="$newdir" 
  fi
}

set_srv_pids() {
   SRV_PIDS=`UNIX95=1 COLUMNS=254 ps -eo pid,args | grep BOOMSERVERPROC | grep java | awk '{print $1}'` 
   if [ -n "$SRV_PIDS" ]
   then
     return 0
   fi
   
   #here are some platform specifics
   osname=`uname`
   case "$osname" in
    HP*) SRV_PIDS=`UNIX95=1 COLUMNS=254 ps -exo pid,args | grep BOOMSERVERPROC | grep java | awk '{print $1}'` 
       ;;
	FreeBSD*) SRV_PIDS=`UNIX95=1 COLUMNS=254 ps -ao pid,args | grep BOOMSERVERPROC | grep java | awk '{print $1}'` 
       ;;
    Sun*)
        if [ -x /usr/ucb/ps ]
        then
          SRV_PIDS=`/usr/ucb/ps -axww | grep BOOMSERVERPROC | grep java | nawk '{print $1}'` 
        else
          if [ -x /usr/bin/pargs ]
          then
            JAVA_PIDS=`UNIX95=1 ps -eo pid,args | grep java | nawk '{print $1}'`
            if  [ -z "$JAVA_PIDS" ]
            then
              SRV_PIDS=
            else
              for i in "$JAVA_PIDS"
              do
                isBOOM=`pargs -l $i  | grep BOOMSERVERPROC`
                if  [ -n "$isBOOM" ]
                then
                  SRV_PIDS="$SRV_PIDS $i"
                fi
              done
            fi
          else
            #last fallback: use PID file and check if it is a java pocess
            LASTPID=`cat $BOOM_SERVER/boom_server.pid`
            SRV_PIDS=`UNIX95=1 COLUMNS=254 ps -eo pid,args -p $LASTPID | grep java | grep "\-jar" | nawk '{print $1}'` 
          fi
        fi
       ;;
    *) SRV_PIDS=`UNIX95=1 COLUMNS=254 ps -eo pid,args | grep BOOMSERVERPROC | grep java | awk '{print $1}'` 
       ;;
    esac
    return 0
}

 #Send kill to all processes of SRV_PIDS
 #Parameter $1 is empty or the kill signal 
stop_pids() { 
    if [ -z "$1" ]
    then
      KSIG=""
    else
      KSIG=$1
    fi
    if [ -z "$SRV_PIDS" ]
    then 
      return 0
    fi
    KILL_OK="YES"
    for i in "$SRV_PIDS"
    do
      if kill $KSIG $i; then
        continue           
      else
        KILL_OK="NO"
        echo "Unable to stop process $i"
      fi 
    done
    if [ "$KILL_OK" = "YES" ]
    then
		if [ -f /var/lock/subsys/boom_srv ]
		then
			rm -f /var/lock/subsys/boom_srv
		fi
      return 0
    else
      return 1
    fi 
}

force_stop() {
    set_srv_pids
    if [ -z "$SRV_PIDS" ]
    then 
      return 0
    fi
    stop_pids 
    sleep 10
    set_srv_pids
    if [ -z "$SRV_PIDS" ]
    then 
      return 0
    fi
    stop_pids -9
    set_srv_pids
    if [ -z "$SRV_PIDS" ]
    then 
      return 0
    else 
      echo "BOOM Server could not be stopped."
      return 1
    fi
}

stop_server() {
    set_srv_pids
    if [ -z "$SRV_PIDS" ]
    then 
      return 0
    fi
    stop_pids
    return $?
}

start_server() {
    cd "$BOOM_SERVER"
    set_srv_pids
    if [ -z "$SRV_PIDS" ]
    then
      osname=`uname`
      case "$osname" in
        HP*) CMD_ARGS="-XX:+UseGetTimeOfDay"
         ;;
        *) CMD_ARGS=
         ;;
      esac

      nohup ${JAVA_BIN}/java -DBOOMSERVERPROC ${JAVA_OPTS} ${CMD_ARGS} --add-modules=ALL-SYSTEM --add-exports java.base/sun.security.pkcs10=boom.server --add-exports java.base/sun.security.x509=boom.server --add-exports java.base/sun.security.pkcs=boom.server --add-exports java.base/sun.security.util=boom.server -p srv/libs  -m boom.server/com.blixx.server.ServerEngine > boom_server_start.log 2>&1 </dev/null &

      cd "$curdir"
      return 0
    else
      echo "BOOM Server is already running."
    fi
    cd "$curdir"

	if [ -d /var/lock/subsys ]
    then
      sh -c "touch /var/lock/subsys/boom_srv" 1>/dev/null 2>&1
    fi
    return 0
}

#get_init_sys
#determine which init mechanism is used on the current system
get_init_sys() {
  SYS_INIT=
  if [ "$OSNAME" = "freebsd" ]; then
    init_s=`ps -aux | grep "init" | grep -v grep | awk '{print $2}' | grep -w "1"`
  else
    init_s=`ps -ef | grep "init" | grep -v grep | awk '{print $2}' | grep -w "1"`
  fi
  if [ "$init_s" = "1" ]; then
     SYS_INIT="init"
     return 0
  fi

  init_s=`ps -ef | grep "systemd" | grep -v grep | awk '{print $2}' | grep -w "1"`
  if [ "$init_s" = "1" ]; then
     SYS_INIT="systemd"
     return 0
  fi

  if [ -z "$SYS_INIT" ]; then
    echo "The Init System used on this server is not or not fully supported by this install skript"
    echo "Some manual installation steps might be required"
    SYS_INIT="unknown"
    return 1
  fi

  return 0
}

#wait4pid
#wait untill the pid file gets updated
wait4pid() {
  i=0
  while [ $i -le 120 ]
  do
    (( i++ ))
    sleep 1

    SRVPID_NEW=
    if [ -f "$BOOM_SERVER/boom_server.pid" ]; then
      SRVPID_NEW=`cat "$BOOM_SERVER/boom_server.pid"`
      if [ -n "$SRVPID_NEW" ]; then
        if [ "$SRVPID_OLD" != "$SRVPID_NEW" ]; then
           sleep 1
           return 0
        fi
      fi
    fi
  done

  echo "PID file is not created. Timeout (120 sec) is exceeded. Exit. "
  exit 2
}

 curdir=`pwd`
 if [ -z "$BOOM_SERVER" ]
 then
   getdir boom_srv "$0"
   if [ -z "$PROG_DIR" ]
   then
     echo "Failed to identify the path for BOOM_SERVER."
     echo "Please set the BOOM_SERVER variable to the Server directory and rerun the script."
     exit 2
   fi
   cd "$PROG_DIR"
   BOOM_SERVER=`pwd`;export BOOM_SERVER
   #echo "Set BOOM_SERVER="$BOOM_SERVER
 fi

# get values from the boom_srv.cfg config file

SRV_CFG_FILE="$BOOM_SERVER/boom_srv.cfg"

if [ -f "$SRV_CFG_FILE" ]
then
  JAVA_OPTS_TMP=`sed '/^\#/d' ${SRV_CFG_FILE} | grep 'JAVA_OPTS' | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | sed 's/^\"\(.*\)\"$/\1/'`
  JAVA_BIN_TMP=`sed '/^\#/d' ${SRV_CFG_FILE} | grep 'JAVA_BIN' | tail -n 1 | cut -d "=" -f2- | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | sed 's/^\"\(.*\)\"$/\1/'`
else
  echo "Configuration file 'boom_srv.cfg' does not exist."
  echo "Default values will be used."
fi

if [ -n "$JAVA_OPTS_TMP" ]
then
  JAVA_OPTS=$JAVA_OPTS_TMP
fi

if [ -n "$JAVA_BIN_TMP" ]
then
  if [ -d "$JAVA_BIN_TMP" ]
  then
    PATH=${JAVA_BIN_TMP}:${PATH}
    export PATH
	JAVA_BIN=${JAVA_BIN_TMP}
  else
    if [ $1 = "-start" ]
    then
      echo "JAVA_BIN=$JAVA_BIN_TMP is not a directory!"
      echo "Default 'java' ($JAVA_BIN) will be used."
      echo "If you need a special 'java' version either run install script first or"
      echo "correct the setting of JAVA_BIN in 'boom_srv.cfg' and rerun this script."
    fi
  fi
fi

 get_init_sys

 case "$1" in

    "-start_msg")
       echo "Starting BOOM Server"
       ;;

    "-start")
       echo "Starting BOOM Server"
	   if [ "$SYS_INIT" = "systemd" ]; then
			systemctl start boom_srv.service
			exit $?
	   fi
       start_server
       exit 0
       ;;


  "-status")
       set_srv_pids
       if [ -z "$SRV_PIDS" ]
       then
         echo "Boom Server is stopped"
         exit 3
       else
         echo "Boom Server is running"
       fi
       exit 0
       ;;

  "-restart")
		if [ "$SYS_INIT" = "systemd" ]; then
         systemctl restart boom_srv.service
         exit $?
		else
         force_stop
		 start_server
		fi
       
       ;;
	   
  "-start_wait")
		echo "Starting BOOM Server"
		SRVPID_OLD=
		if [ -f "$BOOM_SERVER/boom_server.pid" ]; then
		  SRVPID_OLD=`cat "$BOOM_SERVER/boom_server.pid"`
		fi

		start_server
		wait4pid
		exit 0
	  ;;

    "-stop_msg")
       echo "Stopping BOOM Server"
       ;;

    "-stop")
       echo "Stopping BOOM Server"
       stop_server
       exit $?
       ;;


    *) echo "Usage: boom_srv -start|-restart|-status|-stop"
       ;;
esac

exit 0;

