#!/bin/sh
# geninitrd mod: dmraid
USE_DMRAID=${USE_DMRAID:-yes}

# if we should init dmraid at boot
have_dmraid=no

# setup geninitrd module
# @access	public
setup_mod_dmraid() {
	dmraid=$(find_tool $initrd_dir/dmraid /sbin/dmraid-initrd)
	if [ ! -x /sbin/dmraid ] || [ ! -x "$dmraid" ]; then
		USE_DMRAID=no
	fi

	if [ "$kernel_version" -lt "002006" ]; then
		USE_DMRAID=no
	fi
}

# return true if dmraid is set on $devpath
# @param	string $devpath device node to be examined
# @access	public
is_dmraid() {
	local devpath="$1"

	# dmraid disabled
	if ! is_yes "$USE_DMRAID"; then
		return 1
	fi

	if ! is_yes "$(echo "$devpath" | awk '/^\/dev\/mapper\/(sil|hpt37x|hpt45x|isw|lsi|nvidia|pdc|sil|via|dos)_/ { print "yes"; }')"; then
		return
	fi
}

# find dmraid modules for $devpath
# @param	$devpath	device to be examined
# @return	false if $devpath is not on dmraid
# @access	public
find_modules_dmraid() {
	local devpath="$1"

	# get blockdev itself (without partition)
	# /dev/mapper/sil_ahbgadcbchfc3 -> /dev/mapper/sil_ahbgadcbchfc
	local blockdev=${devpath%%[0-9]*}
	local raidname=${blockdev#/dev/mapper/}
	local found=0

	local dev phydevs=$(dmraid -r -cdevpath,raidname | awk -F, -vv="$raidname" '{if ($2 == v) print $1}')
	for dev in $phydevs; do
		find_modules_for_devpath $dev
		lvm_ignore_devices="$lvm_ignore_devices $dev"
		found=1
	done

	if [ $found = 0 ]; then
		return 1
	fi

	find_module "dm-mirror"
	have_dmraid=yes
	return 0
}

# generate initrd fragment for dmraid
# @access	public
initrd_gen_dmraid() {
	if ! is_yes "$have_dmraid"; then
		return
	fi

	inst_d /sbin
	inst_exec $dmraid /sbin/dmraid

	mount_dev
	mount_sys
	initrd_gen_devices
	add_linuxrc <<-EOF
		# 2 secs was enough for my system to initialize.
	   	# XXX: shouldn't just call 'udevadm settle' ?
		usleep 2000000
		: 'Activating Device-Mapper RAID(s)'
		/sbin/dmraid -ay -i

		debugshell
	EOF
}
