#!/usr/bin/sh

PATH=/bin:/sbin:/usr/bin:/usr/sbin
CONFIG=/etc/vdev_id.conf
PHYS_PER_PORT=
DEV=
MULTIPATH=
TOPOLOGY=
BAY=

usage() {
        cat << EOF
Usage: vdev_id [-h]
       vdev_id <-d device> [-c config_file]

  -c    specify name of alernate config file [default=$CONFIG]
  -d    specify basename of device (i.e. sda)
  -h    show this summary
EOF
        exit 0
}

alias_handler () {
        local DM_PART=
        if echo $DM_NAME | grep -q -E 'p[0-9][0-9]*$' ; then
                if [ "$DEVTYPE" != "partition" ] ; then
                        DM_PART=`echo $DM_NAME | awk -Fp '/p/{print "-part"$2}'`
                fi
        fi

        # DEVLINKS attribute must have been populated by already-run udev rules.
        for link in $DEVLINKS ; do
                # Remove partition information to match key of top-level device.
                if [ -n "$DM_PART" ] ; then
                        link=`echo $link | sed 's/p[0-9][0-9]*$//'`
                fi
                # Check both the fully qualified and the base name of link.
                for l in $link `basename $link` ; do
                        alias=`awk "\\$1 == \"alias\" && \\$3 == \"${l}\" \
                                        { print \\$2; exit }" $CONFIG`
                        if [ -n "$alias" ] ; then
                                echo ${alias}${DM_PART}
                                return
                        fi
                done
        done
}

while getopts 'c:d:g:mp:h' OPTION; do
        case ${OPTION} in
        c)
                CONFIG=${OPTARG}
                ;;
        d)
                DEV=${OPTARG}
                ;;
        h)
                usage
                ;;
        esac
done

if [ ! -r $CONFIG ] ; then
        exit 0
fi

if [ -z "$DEV" ] ; then
        echo "Error: missing required option -d"
        exit 1
fi
# First check if an alias was defined for this device.
ID_VDEV=`alias_handler`

if [ -n "$ID_VDEV" ] ; then
        echo "ID_VDEV=${ID_VDEV}"
        echo "ID_VDEV_PATH=disk/by-vdev/${ID_VDEV}"
        echo "ID_VDEV_ALT_PATH=${ID_VDEV}"
fi
