#!/bin/sh
#
# besclient:    Starts the BigFix Client
#
# chkconfig: 2345 99 99
# description: Starts and stops the BigFix Client daemon
# processname: BESClient

export SYSTEMCTL_SKIP_REDIRECT=1

# Source function library.
. /etc/init.d/functions

prog=BESClient

test -x /opt/BESClient/bin/$prog || exit 0

start() {
	/bin/echo -n $"Starting BigFix: $prog: "
	export XAUTHORITY=/root/.Xauthority
	export DISPLAY=:0
	export BESClientActionMastheadPath=/etc/opt/BESClient/actionsite.afxm
	if [ ! -f $BESClientActionMastheadPath ]; then
		failure "Missing masthead $BESClientActionMastheadPath."
		/bin/echo
		return 1
	fi
	# export BES_LIBPATH=/opt/BESClient/bin
	config=/var/opt/BESClient/besclient.config
	if [ ! -f $config ]; then
		if [ ! -f $config.default ]; then
			failure "Missing config file $config."
			/bin/echo
			return 1
		fi
	fi
	# limit access to client created files
	umask 077
	daemon /opt/BESClient/bin/$prog
	ret=$?
	[ $ret -eq 0 ] && /bin/touch /var/lock/subsys/$prog
	/bin/echo
	return $ret
}

stop() {
	/bin/echo -n $"Stopping BigFix: $prog: "
	# Find pid.
	pid=`pidof /opt/BESClient/bin/$prog`
	if [ -z "$pid" ]; then
		ret=1
		RC=0
	else    
		delay=120 
		/bin/kill -TERM $pid >/dev/null 2<&1
		ret=$? 
		usleep 200000
		count=0
		while checkpid $pid && [ "$count" -lt "$delay" ];
		do sleep 5; count=$(($count+5));
		done 
		if [ "$count" -ge "$delay" ]; then 
			kill -KILL $pid >/dev/null 2<&1
			ret=$?
		fi
		usleep 200000
		checkpid $pid
		RC=$?
	fi
	[ "$RC" -eq 0 ] && failure $"BESClient shutdown" || success $"BESClient shutdown"
		RC=$((! $RC))
	[ $ret -eq 0 ] && rm -f /var/lock/subsys/$prog
	/bin/echo
	return $ret
}

restart() {
	stop
	start
}

reload() {
	restart
}

status_BESClient() {
	status /opt/BESClient/bin/$prog
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	condrestart)
		if [ -f /var/lock/subsys/$prog ]; then
			restart
		fi
		;;
	reload|restart)
		restart
		;;
	status)
		status_BESClient
		;;
	*)
		/bin/echo $"Usage: besclient {start|stop|status|restart|reload|condrestart}"
		exit 1
esac

exit $?
