#! /bin/sh

# The following streams are used to configure initrd:

# 3 = modules
# 4 = files
# 5 = script
# 6 = exe
# 7 = modules.2

evms_root() {
    # Make sure all of the low level EVMS plugins are available.
    # We can skip the fsim plugins as they're only used in the GUI

    local plugins
    local skip_plugins

    plugins=$(echo /lib/evms/*/*.so)
    skip_plugins="csm ext2 ha jfs ogfs reiser replace rsct swap xfs ntfs ocfs2 fat"

    for plugin in $plugins; do
	plugin_name=$(echo "$plugin" | sed -e 's,.*/\([^-]*\)-.*$,\1,')
	skip=0
	for excluded in $skip_plugins; do
	    if [ "$plugin_name" = "$excluded" ]; then
		skip=1
		break
	    fi
	done
	if [ $skip -eq 1 ]; then
	    continue
	fi

	# echo them to the exe area so that plugin dependencies are
	# found as well

	echo $plugin >&6
    done

    {
	echo /sbin/evms_activate
	echo /bin/mkdir
    } >&6

    {
	echo /etc/evms.conf
    } >&4


    find "$MODULEDIR/kernel/drivers/md" -name "*.$o" -printf '%f\n' | \
    	sed 's%\.'$o'$%%' >&3


    # Add the following EVMS specific startup script to initrd
    cat >&5 <<- 'EOF'
	case "${CMDROOT:-$ROOT}" in
	    /dev/evms/*)
		mkdir /devfs/evms

		evms_activate
		evms_rootdevnum=$(evms_activate -q --devnum "$ROOT")
		evms_rootdevnum=$evms_rootdevnum
		echo "$evms_rootdevnum" > proc/sys/kernel/real-root-dev
		echo "real-root-dev=$(cat proc/sys/kernel/real-root-dev)"
		break;
		;;
	esac
EOF
}

evms_probe() {
    major="$1"
    minor="$2"

    # EVMS created compatability nodes for devices that it doesn't 
    # manage.  To work around that problem, we require that 
    # an EVMS managed device starts with /dev/evms.

    if (echo ${root} | grep -v "^/dev/evms/" 2>/dev/null >/dev/null); then return; fi

    for vol in /dev/evms/* /dev/evms/md/* /dev/evms/lvm/* /dev/evms/lvm/*/*; do
        if [ ! -b "$vol" ]; then
            continue
        fi

	vol_major_hex=$(stat -c '%t' "$vol")
	vol_minor_hex=$(stat -c '%T' "$vol")
	vol_major=$(printf "%d" 0x$vol_major_hex)
	vol_minor=$(printf "%d" 0x$vol_minor_hex)
        if [ $vol_major = $major -a $vol_minor = $minor ]; then
	    evms_root
            ROOT_ON_EVMS=$vol
	    export ROOT_ON_EVMS

	    DEVLINKS="$DEVLINKS evms"

	    # load kernel modules for physical disks that form the root volume
	    for disk in $(evms_query disks $vol) ; do
		getroot -s /dev/$disk
	    done

            ok=1
            break
        fi
    done
}

register_probe evms_probe
