#!/bin/bash
#
# chkconfig: 345 94 14 
# sgraid is used to start/stop the sgraidmon daemon
#
#. /etc/init.d/functions

# LSB compliant service control script; see http://www.linuxbase.org/spec/
# 
# Template system startup script for some example service/daemon sgraid
#
### BEGIN INIT INFO
# Provides:          sgraid
# Required-Start:    boot.proc boot.md
# X-UnitedLinux-Should-Start: boot.swap
# Required-Stop:     boot.md
# X-UnitedLinux-Should-Stop: 
# Default-Start:     2 3 5
# Default-Stop:      0 1 6
# Short-Description: sgraidmon daemon
# Description:       Start sgraidmon, a monitor for software
#	RAID-1 devices.
### END INIT INFO
# 

SGRAIDMON_BIN=/sbin/sgraidmon
test -x $SGRAIDMON_BIN || exit 5

. /etc/rc.status
rc_reset
  

case "$1" in 
    start)
	echo -n "Starting sgraidmon "
	# Is it already started?
	checkproc $SGRAIDMON_BIN
	if [ $? -eq 0 ]; then
	    echo "sgraidmon is already running"
	    exit 0
	fi
	# Could probably skip the mdevt Save if it was already done once.
	# Get the first disk device configured in /etc/raidtab via getmd
	rdev=`getmd |cut -f2 -d' '`
	# Get full-disk devs
	rdev=`echo "$rdev" | sed 's/part[0-9]$/disc/'`
	rdev=`echo "$rdev" | sed 's/-*p[0-9]*$//'`
	rdev=`echo "$rdev" | sed 's/[0-9]*$//'`
	# Is the rdev disk device active in the raid?
	cat /proc/mdstat |grep $rdev >/dev/null 2>&1
	if [ $? -eq 0 ]
	then 
	   # Active, so save its partition configuration
	   mdevt Save /dev/$rdev
	   rc_status
	fi
	sgraidmon -b 
	rc_status -v
	;;
    stop)
	echo -n "Stopping sgraidmon "
	killproc -TERM $SGRAIDMON_BIN
	rc_status -v
	;;
    status)
	echo -n "Checking for sgraidmon "
	checkproc $SGRAIDMON_BIN
	rc_status -v
	;;
    restart)
        $0 stop
	$0 start	
	rc_status
	;;
    try-restart)
    	$0 status >/dev/null &&  $0 restart
	rc_status
	;;
    reload)
	rc_failed 3
	rc_status -v
	;;
    force-reload)
	$0 stop  &&  $0 start
	rc_status
	;;
    *)
	echo "Usage: $0 start|stop|status|restart|try-restart|reload|force-reload"
	exit 1
	;;
esac
rc_exit
