#!/bin/bash
#
# For RedHat and MontaVista
# chkconfig: 345 94 14 
# processname: sgraidmon
# description: sgraid is used to start/stop the sgraidmon software raid1 daemon
#
### BEGIN SLES INIT INFO
# Provides: sgraid
# Required-Start: $local_fs
# Default-Start:  3 4 5
# Default-Stop:   0 1 2 6
# Description: sgraid is used to start/stop the sgraidmon software raid1 daemon
### END INIT INFO

if [ -f /etc/SuSE-release ]; then
        osver=suse
elif [ -f /etc/redhat-release ]; then
        osver=redhat
elif [ -f /etc/mvl-release ]; then
        osver=mvl
else
        osver=unknown
fi

# Dont need functions any more
#if [ $osver = suse ]
#then
#	. /etc/rc.status
#else
#	. /etc/init.d/functions
#fi

case "$1" in 
"start")
	# Is sg module loaded?
	lsmod | grep sg >/dev/null
        if [ $? -ne 0 ]
	then
	   modprobe sg
	fi
	# Is it already started?
	rpid=`ps -ef |grep sgraidmon |grep -v grep |awk '{print $2}'`
	if [ "${rpid}" != "" ]
	then
	    echo "sgraidmon is already started"
	    exit 1
	fi
	# Could probably skip the 'mdevt Save' if it was already done once.
	# Get the first disk device configured in /etc/raidtab via getmd
        if [ -d /dev/scsi/host0 ]
        then
           rdev=`getmd |cut -f2 -d' ' |sed -e 's/part./disc/'`
        else
           rdev=`getmd |cut -f2 -d' ' |sed -e 's/[0-9]//'`
        fi
	# 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
	fi
	sgraidmon -b 
	touch /var/lock/subsys/sgraidmon 
	;;
"stop")
	rpid=`ps -ef |grep sgraidmon |grep -v grep |awk '{print $2}'`
	if [ "${rpid}" != "" ]
	then
	   kill $rpid
	fi
	rm -f /var/lock/subsys/sgraidmon 
	;;
*)
        echo "Usage: $0 start|stop"
	exit 1
	;;
esac

exit 0
