#!/bin/bash
#%stage: softraid
# grep needed for udev rules file.
#%programs: /sbin/mdadm /sbin/mdmon
#%modules: raid0 raid1 raid10 raid456
#%if: -n "$need_mdadm"
#
##### MD (Software-)Raid
##
## This activates and waits for an MD software raid.
##
## Command line parameters
## -----------------------
##
## need_mdadm=1		use MD raid
## 

# load the necessary module before we initialize the raid system
load_modules

# put the mdmon socked and pid file to /dev/.mdadm
rm -rf /var/run/mdadm
mkdir -p /var/run
ln -s /dev/.mdadm /var/run/mdadm
mkdir -p /dev/.mdadm
[ "$mduuid" ] && md_uuid="$mduuid"

md_major=$(sed -ne 's/\s*\([0-9]\+\)\s*md$/\1/p' /proc/devices)
if [ -n "$md_major" -a "$md_major" = "$maj" ]; then
    md_minor="$min"
    md_dev="/dev/md$md_minor"
fi

# Always start md devices read/only. They will get set to rw as soon
# as the first write occurs. This way we can guarantee that no
# restore occurs before resume.
if [ -f /sys/module/md_mod/parameters/start_ro ]; then
    echo 1 > /sys/module/md_mod/parameters/start_ro
fi

if test -n "$debug_linuxrc"; then
	mdadm="mdadm -v"
else
	mdadm="mdadm"
fi

# uuid -> array name
get_md_name()
{
	local uuid=$1 res

	if ! test -f /etc/mdadm.conf; then
		return 1
	fi
	res=$(sed -rn "s/^ARRAY +([^ ]+).* UUID=$uuid.*/\1/p" /etc/mdadm.conf)
	case "$res" in
	"" | \<* | *=*)
		return 1
		;;
	/*)
		echo "$res"
		;;
	*)
		echo "/dev/md/$res"
		;;
	esac
	return 0
}

md_assemble()
{
	local dev=$1 uuid mdconf container container_name

	if test -e "$dev"; then
		return
	fi
	case "$dev" in
	/dev/md[0-9]*p[0-9]*)
		dev=${dev%p[0-9]*}
		;;
	/dev/md*)
		;;
	/dev/disk/by-id/md-uuid-*)
		uuid=${dev#/dev/disk/by-id/md-uuid-}
		uuid=${uuid%-part*}
		dev=
		;;
	*)
		return
	esac
	if test -f /etc/mdadm.conf; then
		mdconf="-c /etc/mdadm.conf"
		local line
		if test -n "$dev"; then
			line=$(sed -rn "\:^ARRAY +$dev :p" /etc/mdadm.conf)
		else
			line=$(sed -rn "/^ARRAY .* UUID=$uuid/p" /etc/mdadm.conf)
		fi
		container=$(echo "$line" | \
			sed -rn 's/.* container=([^ ]*).*/\1/p')
	else
		mdconf="-c partitions"
	fi
	case "$container" in
	"")
		;;
	/dev/*)
		$mdadm -A $mdconf $container
		;;
	[0-9a-f]*[0-9a-f])
		container_name=$(get_md_name "$container")
		if test -z "$container_name"; then
			container_name=/dev/md/container
		fi
		$mdadm -A $mdconf --uuid="$container" "$container_name"
		;;
	*)
		echo "unrecognized container for $dev: $container"
	esac
	if test -n "$dev"; then
		$mdadm -A $mdconf "$dev"
	else
		dev=$(get_md_name "$uuid")
		if test -z "$dev"; then
			# mdadm will pick a device name
			$mdadm -A $mdconf --uuid=$uuid
		else
			$mdadm -A $mdconf --uuid=$uuid "$dev"
		fi
	fi
}

md_assemble "$resumedev"
md_assemble "$rootdev"
if [ -n "$md_dev" ] ; then
	md_assemble "$md_dev"
fi
# assemble any md devices seen by setup-md.sh at initrd build time
for dev in $md_devs; do
	md_assemble "$dev"
done

wait_for_events
