#! /bin/bash
#
# centreon_vmware          Start/Stop the centreon_vmware daemon.
#
# chkconfig: 2345 80 20
# description: centreon_vmware is a Centreon program that manage Vpshere Checks
# processname: centreon_vmware.pl
# config: /etc/centreon/centreon_vmware.pm
# pidfile: /var/run/centreon_vmware.pid

# Source function library.
. /etc/init.d/functions
  
binary=/usr/bin/centreon_vmware.pl
servicename=$(basename "$0")
OPTIONS=""
user=root
timeout=60
start_timeout=5

pidfile=/var/run/centreon_vmware.pid

[ -e /etc/sysconfig/centreon_vmware ] && . /etc/sysconfig/centreon_vmware

# Check if we can find the binary.
if [ ! -x $binary ]; then
    echo -n $"Starting $servicename.";
    failure $"Executable file $binary not found. Exiting."
    echo
    exit 2
fi

start() {
	echo -n $"Starting $servicename: "
        if [ -e "$pidfile" ] && [ -n "$(cat $pidfile)" ] && [ -e "/proc/`cat $pidfile`" ]; then
                echo -n $"cannot start $servicename: $servicename is already running.";
                failure $"cannot start $servicename: $servicename already running.";
                echo
                return 1
        fi
        if [ ! -e "$pidfile" ] ; then
                pid=$(pidofproc $binary)
                if [ -n "$pid" ] ; then
                        echo -n $"cannot start $servicename: $servicename is already running.";
                        failure $"cannot start $servicename: $servicename already running.";
                        echo
                        return 1
                fi
        fi

	if [ "$(id -u -n)" = "$user" ] ; then
		daemon --check centreon_vmware ''$binary' '$OPTIONS' > /dev/null 2>&1 &'
	else
		daemon --user $user --check centreon_vmware ''$binary' '$OPTIONS' > /dev/null 2>&1 &'
	fi
    
    sleep 2

    i=0
	while : ; do
		if [ "$i" -gt $start_timeout ] ; then
			failure $"service not launched"
			echo
			return 1
		fi
		pid=$(pidofproc $binary)
		if [ -n "$pid" ] ; then
			echo $pid > $pidfile
			break
		fi
		sleep 1
		i=$(($i + 1))
	done
	success $"service launched"
	echo
	return 0
}

stop() {
	echo -n $"Stopping $servicename: "
        if [ ! -e "$pidfile" ] || [ -z "$(cat $pidfile)" ] ; then
                killproc -d $timeout "$binary"
        else
                killproc -p "$pidfile" -d $timeout "$binary"
        fi
        RETVAL=$?
        echo
        return $RETVAL
}	

rhstatus() {
	status -p "$pidfile" "$binary"
}	

restart() {
  	stop
	start
}	

reload() {
	echo -n $"Reloading $servicename daemon configuration: "
        killproc -p "$pidfile" "$binary" -HUP
        RETVAL=$?
        echo
        return $RETVAL
}	

case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart)
  	restart
	;;
  reload)
  	reload
	;;
  status)
  	rhstatus
	;;
  condrestart)
  	[ -f /var/lock/subsys/centreon_vmware ] && restart || :
	;;
  *)
	echo $"Usage: $0 {start|stop|status|reload|restart|condrestart}"
	exit 1
esac


