#!/bin/sh
#
# Startup RAID-arrays that aren't already running, or stop
# all active arrays mentioned in raidtab.
#
# Written by Rainer Weikusat <weikusat@students.uni-mainz.de>
# Some modifications by Pekka Aleksi Knuutila <pa@debian.org>

#*  parameters
#
PATH=/sbin:/bin

RAIDSTART=/sbin/raidstart
RAIDSTOP=/sbin/raidstop
RAID0RUN=/sbin/raid0run
CONFIG=/etc/raidtab

#*  functions
#
list_devices()
{
    sed 's/#.*$//' $CONFIG | grep raiddev | while read REPLY;
    do
        set -- $REPLY
        echo $2
    done
}

is_active()
{
    # remove the leading /dev/, and possibly / from the middle
    NAME=$(echo $1 | sed -e 's/^\/dev\/\(md\)\/*\(.*\)$/\1\2/')
    
    grep -q "^$NAME : active" /proc/mdstat
}

read_param()			# $1: raiddev $2: param-name
{
    DEV="$1"
    PARAM="$2"
    
    sed 's/#.*$//' $CONFIG | while read REPLY;
    do
    set -- $REPLY
	
    if [ "$1" = raiddev -a "$2" = $DEV ];
    then
        while read REPLY;
        do
            set -- $REPLY
            
            if [ "$1" = raiddev ];
            then
                break
            fi
            
            if [ "$1" = $PARAM ];
            then
                echo $2
            fi
        done
        return
    fi
    done
}

start_device()
{
    DEV="$1"
    
    if [ "$(read_param $DEV persistent-superblock)" != 0 ];
    then
        $RAIDSTART --configfile $CONFIG $DEV && echo -n "$DEV "
    else
        case "$(read_param $DEV raid-level)" in
            0|linear)
            $RAID0RUN --configfile $CONFIG $DEV && echo -n "$DEV "
            ;;
	    
            *)
            echo "Cannot auto-start old-style $DEV. See mkraid(8), -o" >&2
            ;;
        esac

    fi
}

#*  main code
#
if [ ! -f /proc/mdstat -a -x /sbin/modprobe ]; then
    modprobe -k md > /dev/null 2>&1  
fi
if [ ! -f /proc/mdstat ]; then
    echo 'raidtools2 init script failed; RAID drivers not available.' >&2 
	exit 1
fi

test -f $CONFIG || exit 0

case "$1" in
    start)
    test -x $RAIDSTART && test -x $RAID0RUN || exit 0

    echo -n 'Starting RAID devices: '

    list_devices | while read REPLY;
    do
        is_active $REPLY && continue
        start_device $REPLY
    done

    echo done.
    ;;

    stop)
    test -x $RAIDSTOP || exit 0

    echo -n 'Stopping RAID devices: '

    list_devices | while read REPLY;
    do
        is_active $REPLY || continue
        $RAIDSTOP --configfile $CONFIG $REPLY && echo -n "$REPLY "
    done

    echo done.
    ;;

    restart|reload|force-reload)
    $0 stop
    sleep 2
    $0 start
    ;;
esac
