#!/bin/bash
# 
# mdmonitor	This starts, stops, and reloads the mdadm-based
#		software RAID monitoring and management facility
#
# chkconfig: 2345 99 99
# description: software RAID monitoring and management
# config: /etc/mdadm.conf
#

# Copyright 2002 Red Hat, Inc.

#PATH=/sbin:/usr/sbin:$PATH
RETVAL=0
MDADM_BIN=/usr/local/sbin/mdadm
MD_PROG=/usr/local/sbin/mdadm-events
MDADM_PID=/var/run/mdadm.pid
prog=mdmonitor
DEV=/dev/md0

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

# Make sure configuration file exists and has information we can use
# MAILADDR or PROGRAM or both must be set in order to run mdadm --monitor
[ -f /etc/mdadm.conf ] || exit 0
grep '^\(MAILADDR\|PROGRAM\) .' /etc/mdadm.conf >/dev/null 2>&1 || exit 0


usage ()
{
    echo "Usage: service $prog {start|stop|status|restart|condrestart}"
    RETVAL=1
}


start ()
{
    #ulimit -S -c 0 >/dev/null 2>&1
    echo -n $"Starting $prog: "
    # send a one shot message to the monitor for startup
    echo "Array OK $DEV" > /tmp/raidstatus
    $MDADM_BIN --monitor --scan --daemonize --pid-file $MDADM_PID -p $MD_PROG
    # hack: wait for mdadm to die, assume success if it doesn't die quickly
    sleep 1
    if [ -d /proc/$(cat /var/run/mdadm.pid) ] ; then
	echo "success" # $"mdadm"
	RETVAL=0
    else
        echo "failure" # $"mdadm"
	RETVAL=1
    fi
    touch /var/lock/$prog
}

stop ()
{
    pkill mdadm
    rm -f /var/run/mdadm.pid
    rm -f /var/lock/$prog
}

restart ()
{
    stop
    start
}

condrestart ()
{
    [ -e /var/lock/$prog ] && restart
}


case "$1" in
    start) start ;;
    stop) stop ;;
    status) status mdadm ;;
    restart|reload) restart ;;
    condrestart) condrestart ;;
    *) usage ;;
esac

exit $RETVAL
