#!/bin/sh
#
# Copyright 2015 VMware, Inc. All rights reserved.
#
# NSX-SFHC:
#   Start/Stop the NSX Service Fabric Host Component
#
# Tell chkconfig to start us with starting rank 98 and shutdown rank 2.
# chkconfig: 2345 98 2
# description: NSX-SFHC
#

# variables
export PATH=/bin:/sbin:/usr/bin
export LD_LIBRARY_PATH=/opt/vmware/nsx-shared/lib64
NSXSFHC=/opt/vmware/nsx-sfhc/bin/nsx-sfhc
NSXSFHC_TAG=NSX-SFHC
NSXSFHC_MAX_QUICK_RESTARTS="10"
NSXSFHC_MAX_RESTARTS="1000"
WATCHDOG_ARGS="-d -s ${NSXSFHC_TAG} -q ${NSXSFHC_MAX_QUICK_RESTARTS} -t ${NSXSFHC_MAX_RESTARTS}"

WATCHDOG=/opt/vmware/nsx-sfhc/bin/watchdog.sh

sfhc_log() {
   echo "${1}"
   logger -p daemon.info -t NSX "${1}"
}

start() {

   # start NSXSFHC with watchdog
   if [ -z "$(pidof -s "${NSXSFHC}")" ] ; then
      ulimit -n 1024
      ulimit -c unlimited
      ${WATCHDOG} ${WATCHDOG_ARGS} "${NSXSFHC} ${NSXSFHC_ARGS}" >/dev/null 2>&1
      sfhc_log "${NSXSFHC_TAG} started"
   else
      sfhc_log "${NSXSFHC_TAG} already running"
   fi

}

stop() {
   if [ -n "$(pidof -s "${NSXSFHC}")" ] ; then
      # This only stops the watchdog process.
      ${WATCHDOG} -k "${NSXSFHC_TAG}"

      # Use killproc function if available
      if [ "$INITD_FUNCTIONS_BOOL" = true ]; then
         killproc "${NSXSFHC}" -KILL
         sfhc_log "${NSXSFHC_TAG} Using killproc to terminate the process"
      fi

      # Repeat the kill if pid is still found
      local KILL_ATTEMPT=1
      while [ -n "$(pidof -s "${NSXSFHC}")" ] ; do
         pkill -KILL -f "${NSXSFHC}"
         sfhc_log "${NSXSFHC_TAG} Terminating ${NSXSFHC} service. Attempt #$((KILL_ATTEMPT++))"
         if [ $((KILL_ATTEMPT)) -eq 10 ]; then
            sfhc_log "${NSXSFHC_TAG} Unable to terminate ${NSXSFHC}"
            exit 1
         fi
         # Wait for the process to terminate
         sleep 1
      done

      if [ -z "$(pidof -s "${NSXSFHC}")" ] ; then
         sfhc_log "${NSXSFHC_TAG} stopped"
      fi
   else
      sfhc_log "${NSXSFHC_TAG} is not running"
   fi
}

#
# main
#
case "${1}" in
   "start")
      start
   ;;
   "stop")
      stop
   ;;
   "status")
      if [ -n "$(pidof -xs "${NSXSFHC}")" ] ; then
         echo "${NSXSFHC_TAG} is running"
         exit 0
      else
         echo "${NSXSFHC_TAG} is not running"
         # Returning 3 like everyone else.
         exit 3
      fi
   ;;
   "restart")
      stop
      start
   ;;
   *)
      echo "Usage: $(basename ${0}) {start|stop|status|restart}"
      exit 1
   ;;
esac
