#!/bin/bash
#
# Init file for rhnmd daemon
#
# chkconfig: 2345 99 1
# description: rhnmd server daemon
#
# processname: rhnmd

### BEGIN INIT INFO
# Provides: rhnmd
# Required-Start: $local_fs $network $remote_fs
# Required-Stop: $local_fs $network $remote_fs
# Default-Start: 3 5
# Default-Stop: 0 1 6
# Short-Description: rhnmd server daemon
# Description: Provides wrapper around sshd
#       so NOCpulse monitoring can connect to your machine
#       and run probes, which requires local account.
### END INIT INFO

# source function library
. /etc/rc.status

prog="rhnmd"

# Some functions to make the below more readable
SU="/bin/su -s /bin/bash - nocpulse -c"
SSHD="/usr/sbin/rhnmd"
SSHD_PIDFILE="/var/run/rhnmd.pid"

do_restart_sanity_check()
{
	$SU "$SSHD -t -f /etc/nocpulse/rhnmd_config"
	RETVAL=$?
	if [ ! "$RETVAL" = 0 ]; then
		rc_failed
		echo "Configuration file or keys are invalid"
	fi
}

start()
{
	echo -n $"Starting $prog:"
	IDENTITY="/var/lib/nocpulse/.ssh/nocpulse-identity"
	if [ ! -f "$IDENTITY" ]
	then
		/bin/su -s /bin/bash -c "/usr/bin/ssh-keygen -q -t dsa -N '' -f $IDENTITY" - nocpulse
		if [ ! -e "/var/lib/nocpulse/.bashrc" ]; then
			echo 'LANG="C"' > /var/lib/nocpulse/.bashrc
		fi
	fi
	startproc -p $SSHD_PIDFILE $SSHD -f /etc/nocpulse/rhnmd_config -o "PidFile=$SSHD_PIDFILE"
	rc_status
	rc_status -v
}

stop()
{
	echo -n $"Stopping $prog:"
	killproc -p $SSHD_PIDFILE -TERM $SSHD
        rc_status -v
}

reload()
{
	echo -n $"Reloading $prog:"
	killproc -p $SSHD_PIDFILE -HUP $SSHD
	rc_status -v
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		start
		;;
	reload)
		reload
		;;
	condrestart|try-restart)
                $0 status
                if test $? = 0; then
                        do_restart_sanity_check
                        if [ "$RETVAL" = 0 ] ; then
                                $0 stop
                                # avoid race
                                sleep 3
                                $0 start
                        fi
                else
                        rc_reset
                fi
                rc_status
		;;
	status)
	        echo -n "Checking for service rhnmd: "
		checkproc -p $SSHD_PIDFILE $SSHD
		rc_status -v
		;;
	*)
		echo $"Usage: $0 {start|stop|restart|reload|condrestart|try-restart|status}"
esac
rc_exit
