#!/bin/sh
. /lib/svc/share/smf_include.sh

getproparg() {
    val=`svcprop -p $1 $SMF_FMRI`
    [ -n "$val" ] && echo $val
}

status_nrpe ()
{
    pid_nrpe
    if ps -p $NagiosPID > /dev/null 2>&1; then
	return 0
    else
	return 1
    fi
    return 1
}


killproc_nrpe ()
{
    kill $NrpePID
}


pid_nrpe ()
{
    if test ! -f $NrpeRunFile; then
	echo "No lock file found in $NagiosRunFile"
	exit 1
    fi
    NrpePID=`head -n 1 $NrpeRunFile`
}

NrpeBin=`getproparg nrpe/bin`
NrpeCfgFile=`getproparg nrpe/cfgfile`
NrpeRunFile=`getproparg nrpe/runfile`
NrpeLockDir=`getproparg nrpe/lockdir`
NrpeLockFile=`getproparg nrpe/lockfile`
NrpeUser=`getproparg nrpe/user`
NrpeGroup=`getproparg nrpe/group`

if [ -z $SMF_FMRI ]; then
    echo "Error: SMF framework variables are not initialized"
    exit $SMF_EXIT_ERR
fi

# Check that nrpe exists.
if [ ! -x $NrpeBin ]; then
    echo "Executable file $NrpeBin not found.  Exiting."
    exit $SMF_EXIT_ERR_CONFIG
fi

# Check that nagios.cfg exists.
if [ ! -f $NrpeCfgFile ]; then
    echo "Configuration file $NrpeCfgFile not found.  Exiting."
    exit $SMF_EXIT_ERR_CONFIG
fi

# See how we were called.
case "$1" in
  start)
	# Start daemons.
	echo -n "Starting nrpe: "
	touch $NrpeRunFile
	chown $NrpeUser:$NrpeGroup $NrpeRunFile
	$NrpeBin -c $NrpeCfgFile -d
	mkdir -p $NrpeLockDir
	touch $NrpeLockDir/$NrpeLockFile
	echo " done."
	exit 0
	;;
  stop)
	# Stop daemons.
	echo -n "Shutting down nrpe: "
	pid_nrpe	
	killproc_nrpe
	echo
	rm -f $NrpeLockDir/$NrpeLockFile $NrpeRunFile
	;;
  restart)
	$0 stop
	$0 start
	;;
  status)
	status_nrpe
	;;
  *)
	echo "Usage: nrpe {start|stop|restart|status}"
	exit 1
esac

exit $SMF_EXIT_OK
