#!/bin/bash
#chkconfig: 2345 52 48
#description: Chelsio Uwire Manager Agent 


### BEGIN INIT INFO
# Provides:          Chelsio_Uwire_Manager_Agent
# Required-Start:    $network
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 2 6
# Short-Description: Chelsio Unified Wire Manager Agent Daemon
# Description:       The Chelsio Unified Wire Manager Agent daemon 
#	service.  We want it to be active in runlevels 2 3 4
#	and 5, as these are the runlevels with the network
#	available.
### END INIT INFO

RETVAL=0
prog="Chelsio Uwire Manager Agent"
EXP_INSTANCE=0
instance=0
SNMP_INSTANCE=1
OSNAME=`uname -s`
BIN_PATH="/opt/chelsio/uwire_mgmt/agent"
PSCMD="ps -eaf"

start_uwireserver()
{
	$BIN_PATH/runUWServer.sh 1>/dev/null
	RETVAL=$?

	instance=`${PSCMD} | grep UWMgrServer | grep -v grep | wc -l `
	if [ $RETVAL -eq 0 ];
	then
		echo  "Unified Manager Agent : Started"
	elif [ $RETVAL -eq 1 ];
	then
		echo  "Unified Manager Agent : Already Running"
	else 
		echo "Unified Manager Agent : Not Started"
	fi

	return $RETVAL

}

start_umupdate()
{
	$BIN_PATH/umUpdateDaemon 1>/dev/null
}

stop_umupdate()
{
	killall umUpdateDaemon
}

restart_umupdate()
{
	stop_umupdate
	start_umupdate
}

stop_uwireserver() {
	# echo -n $"Stopping $prog: "
	instance=`${PSCMD} | grep UWMgrServer | grep -v grep | wc -l `
	if [ $instance -gt 0 ]; then
		pid=`${PSCMD} |grep UWMgrServer| grep logserver | grep -v grep | awk '{print $2}'`
		kill -INT $pid		
		pid=`${PSCMD} |grep UWMgrServer| grep slp | grep -v grep | awk '{print $2}'`
		kill -INT $pid		
		pid=`${PSCMD} |grep UWMgrServer| grep -v logserver | grep -v slp | grep -v grep | awk '{print $2}'`
		kill -INT $pid
		echo "Unified Manager Agent : Stopped"
	else
		echo "Unified Manager Agent : Not Running"
	fi
	RETVAL=$?
	return $RETVAL
}

status_uwireserver() {
	instance=`${PSCMD} | grep UWMgrServer | grep -v grep | wc -l `
	#Min 3 instances will be running. > 3 when main process forks for e.g driver installation.
	if [ $instance -ge 3 ]; then
	    echo "Unified Manager Agent : Running"
	else
	    echo "Unified Manager Agent : Stopped"
	fi
               
	RETVAL=$?
        return $RETVAL
}

restart_uwireserver(){
	stop_uwireserver
	start_uwireserver
}

if [ $UID -ne 0 ]; then
	echo "chelsio-uwire_mgmtd: Permission denied: Not a root user"
	exit 0
fi

case "$1" in
  start)
	start_uwireserver
	;;
  stop)
	stop_uwireserver
	;;
  status)
	status_uwireserver
	;;
  restart)
	restart_uwireserver
        ;;
  stopUmUpdate)
	stop_umupdate	
	;;
  startUmUpdate)
	start_umupdate
	;;
  *)
	echo "Usage: $0 {start|stop|restart|status}"
	RETVAL=1
esac

exit $RETVAL
