#!/bin/sh

PREREQ="mdadm mdrun multipath"

prereqs()
{
    echo "$PREREQ"
}

case $1 in
# get pre-requisites
prereqs)
    prereqs
    exit 0
    ;;
esac

if [ ! -e /sbin/lvm ]; then
    exit 0
fi

boot_type=""
root_mapper="none"
for x in $LIVE_BOOT_CMDLINE; do
    case $x in
        boot=*)
            boot_type=${x#boot=}
            ;;
        root-mapper=*)
            root_mapper=${x#root-mapper=}
            ;;
    esac
done

if [ "${boot_type}" != "live" ]; then
    exit 0
fi

lvchange_activate() {
    local max_try=10
    while [ $max_try -gt 0 ]; do
        lvm lvchange -aay -y --sysinit --ignoreskippedcluster "$@"
        local retcode=$?
        if [ $retcode = 0 ]; then
            max_try=-1
            return 0
        else
            max_try=$(( $max_try - 1 ))
            sleep 1
        fi
    done
}

activate() {
    local dev="$1"

    # Make sure that we have a non-empty argument
    if [ -z "$dev" ]; then
        return 1
    fi

    case "$dev" in
    # Take care of lilo boot arg, risky activating of all vg
    fe[0-9]*)
        lvchange_activate
        exit 0
        ;;
    # FIXME: check major
    /dev/root)
        lvchange_activate
        exit 0
        ;;

    /dev/mapper/*)
        eval $(dmsetup splitname --nameprefixes --noheadings --rows "${dev#/dev/mapper/}")
        if [ "$DM_VG_NAME" ] && [ "$DM_LV_NAME" ]; then
            lvchange_activate "$DM_VG_NAME/$DM_LV_NAME"
        fi
        ;;

    /dev/*/*)
        # Could be /dev/VG/LV; use lvs to check
        if lvm lvs -- "$dev" >/dev/null 2>&1; then
            lvchange_activate "$dev"
        fi
        ;;
    esac
}

if [ "${root_mapper}" != "none" ]; then
    activate "$root_mapper"
    activate "$resume"
fi

exit 0
