#!/bin/sh
#
# Copyright 2016 VMware, Inc. All rights reserved.
#
# NSX Platform Client:
#   Start/Stop the NSX Platform Client

### BEGIN INIT INFO
# Provides:          nsx-platform-client
# Required-Start:    $network $local_fs
# Required-Stop:     $network $local_fs
# Default-Start:     3 4 5
# Default-Stop:      0 1 6
# Short-Description: NSX Platform Client
### END INIT INFO


# variables
export PATH=/bin:/sbin:/usr/bin:/usr/sbin
export LD_LIBRARY_PATH=/usr/lib/vmware/nsx-mpa
# Workaround for python bug
# See bugzilla.redhat.com BUG ID 880393
# See bugs.python.org issue 19884
export TERM=vt100

PLATFORM=/opt/vmware/nsx-platform-client/bin/nsx-platform-client
PLATFORM_TAG=NSX-Platform-Client
PLATFORM_MAX_QUICK_RESTARTS="10"
PLATFORM_MAX_RESTARTS="1000"
PLATFORM_USER="nsxplatform"
WATCHDOG_ARGS="-d -s ${PLATFORM_TAG} -q ${PLATFORM_MAX_QUICK_RESTARTS} -t ${PLATFORM_MAX_RESTARTS}"

PLATFORM_ARGS=""

WATCHDOG=/opt/vmware/nsx-platform-client/bin/watchdog.sh

INITD_FUNCTIONS_FILE="/etc/rc.d/init.d/functions"
INITD_FUNCTIONS_BOOL=false
# Include source function library if available
if [ -f "$INITD_FUNCTIONS_FILE" ]; then
   INITD_FUNCTIONS_BOOL=true
   . "$INITD_FUNCTIONS_FILE"
fi


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


start() {
   # start PLATFORM with watchdog
   groupadd -f $PLATFORM_USER
   if ! getent passwd $PLATFORM_USER > /dev/null; then
      useradd --system -N -g $PLATFORM_USER --shell /usr/sbin/nologin -M \
      --comment "NSX Platform Client" $PLATFORM_USER
   fi
   if [ -z "$(pidof -s "${PLATFORM}")" ] ; then
      ulimit -n 1024
      ulimit -c unlimited
      ${WATCHDOG} ${WATCHDOG_ARGS} "${PLATFORM} ${PLATFORM_ARGS}" >/dev/null 2>&1
      nsbc_log "${PLATFORM_TAG} started"
   else
      nsbc_log "${PLATFORM_TAG} already running"
   fi
}


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

      # Use killproc function if available
      if [ "$INITD_FUNCTIONS_BOOL" = true ]; then
         killproc "${PLATFORM}" -KILL
      fi

      # Using pkill for safe measure
      pkill -KILL -f "${PLATFORM}"
      nsbc_log "${PLATFORM_TAG} stopped"
   else
      nsbc_log "${PLATFORM_TAG} is not running"
   fi
}

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