#!/bin/sh
#
# dmraid-activate: Script to reformat the output of dmraid to be useful with
# udev.
#
# (c) 2008 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
set -x
set -v

if [ -z "$1" ] || [ "$1" = "--degraded" ] && [ "$#" -lt 2 ]; then
	echo "Node name not specified." >&2
	exit 1
fi

if [ "$1" = "--degraded" ]; then
	Degraded=1
	Node_Name=$2
else
	Node_Name=$1
fi

Raid_Name=$(dmraid -i -r -cr /dev/$Node_Name >> /dev/dmraid.log 2>&1)
Raid_Name=$(dmraid -i -r -cr /dev/$Node_Name | grep -v "No RAID disks")

if [ -z "$Raid_Name" ]; then
	exit 0
fi

Raid_Setinfo=$(dmraid -i -si $Raid_Name)
if [ -z "$Raid_Setinfo" ]; then
	exit 0
fi

Raid_Type=$(dmraid -i -si -ct $Raid_Name)
Raid_Nodevs=$(dmraid -i -si -cd $Raid_Name)

case "$Raid_Type" in
	stripe)
		if [ "$Raid_Nodevs" -lt 2 ]; then
			if [ -n "$Degraded" ]; then
				echo "Cannot bring up a RAID0 array in degraded mode."
			fi
			exit 1
		fi
		;;
	mirror)
		if [ "$Raid_Nodevs" -lt 2 ] && [ -z "$Degraded" ]; then
			exit 1
		fi
		;;
	raid5_*)
		if [ "$Raid_Nodevs" -lt 3 ] && [ -z "$Degraded" ]; then
			exit 1
		fi
		;;
esac

# At this point we have the required number of devs, or the user wants the
# array brought up in degraded mode, except in the case of striped arrays.
if ! grep -q "dm_mod" /proc/modules ; then
	modprobe dm_mod
fi

dmraid -i -ay $Raid_Name

