#!/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 INIT INFO
# Provides: sgraid
# Required-Start: $local_fs
# Required-Stop: $local_fs
# Default-Start:  3 5
# Default-Stop:   0 1 2 6
# Short-Description: sgraidmon daemon
# Description: sgraid is used to start/stop the sgraidmon software raid1 daemon
### END INIT INFO

if [ -f /etc/SuSE-release ] || fgrep -siq suse /etc/os-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")
	echo -n "Starting sgraidmon "
	# 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"
	    rc_failed 1
	    rc_status -v
	    rc_exit
	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 
	rc_status -v
	;;
"stop")
	echo -n "Stopping sgraidmon "
	rpid=`ps -ef |grep sgraidmon |grep -v grep |awk '{print $2}'`
	if [ "${rpid}" != "" ]
	then
	   kill $rpid
	fi
	rc_status -v
	;;
"status")
	echo -n "Checking for sgraidmon "
	rpid=`ps -ef |grep sgraidmon |grep -v grep |awk '{print $2}'`
	if [ "${rpid}" != "" ]
	then
	  echo -n "(pid $rpid)"
	else
	  rc_failed 3
	fi
	rc_status -v
	;;
*)
        echo "Usage: $0 start|stop"
	exit 1
	;;
esac

rc_exit

