#!/bin/bash
#
# hpnragent init script.
#
# chkconfig: 345 99 00
# description: HP NetRAID agent daemon.

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

test -x /usr/hpserver/bin/hpnragent || exit 1


###################################################
# function to create megasnmp device
###################################################
create_megasnmp_device() {
    if [ -d /proc/scsi/megaraid ]; then
        major=$( cat /proc/devices |grep megadev | cut -f1 -d " " )
        if [ ! $major = " " ]; then
	    #if megasnmp exists
	    if [ -c /etc/hpnrsnmp/megasnmp ]; then
		lsdev=`ls -l /etc/hpnrsnmp/megasnmp | cut -d',' -f1`
		let size=${#lsdev}+1
		let size1=$size-3
    		run_major=`echo "$lsdev" | cut -b$size1-$size`
		#if major diff running_major then update
		if [ $major -ne $run_major  ]; then
		    rm -f /etc/hpnrsnmp/megasnmp
		    mknod /etc/hpnrsnmp/megasnmp c $major 0
		fi
	    else
		if [ ! -d /etc/hpnrsnmp ]; then
		    mkdir /etc/hpnrsnmp
		fi
		mknod /etc/hpnrsnmp/megasnmp c $major 0
	    fi
	fi
    fi
    return 0
}

###################################################
# function to destroy the megasnmp device
###################################################
destroy_megasnmp_device() { 
    if [ -c /etc/hpnrsnmp/megasnmp ]; then
	rm -rf /etc/hpnrsnmp
    fi
    return 0
}


###################################################
# start the main part
###################################################
RETVAL=0

#
#	See how we were called.
#
case "$1" in
  start)
	# Check if hpnragent is already running
	if [ ! -f /var/lock/subsys/hpnragent ]; then
	    echo -n 'Starting HP NetRAID agent daemon: '
	    create_megasnmp_device
	    daemon /usr/hpserver/bin/hpnragent
	    RETVAL=$?
	    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/hpnragent
	    echo
	fi
	;;
  stop)
	echo -n 'Stopping HP NetRAID agent daemon: '
	destroy_megasnmp_device
	killproc /usr/hpserver/bin/hpnragent
	RETVAL=$?
	# [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/hpnragent
	rm -f /var/lock/subsys/hpnragent
	echo
	;;
  reload|restart)
	$0 stop
	$0 start
	RETVAL=$?
	;;
  status)
	status /usr/hpserver/bin/hpnragent
	RETVAL=$?
	;;
  *)
	echo "Usage: /etc/rc.d/init.d/hpnragent {start|stop|restart|reload|status}"
	exit 1
esac

exit $RETVAL
