#!/bin/sh

# Resolve device node from a name.  This expands any LABEL or UUID.
resolv_device() {
	DEV="$1"
	local orig="$DEV"

	case "$DEV" in
	LABEL:* | UUID:* | PARTLABEL:* | PARTUUID:*)
        DEV=$(echo ${DEV} | sed 's/:/=/')
		DEV="$(blkid -l -t "$DEV" -o device)"
		if [ "$?" != 0 ]; then
			DEV="$orig"

			# Support uppercase and lowercase UUIDs -- see RFC#4122:
			#   "Each field is treated as an integer and has its value printed as
			#    a zero-filled hexadecimal digit string with the most significant
			#    digit first.  The hexadecimal values "a" through "f" are output as
			#    lower case characters and are case insensitive on input."
			#
			# Note: that blkid which we will use to map these assums the input is lower
			# case.

			# Only apply this behaviour to UUIDs.
			case "$DEV" in
			UUID=* | PARTUUID=*)	;;
			*)			return 1 ;;
			esac

			# Pull DEV appart and map it.
			local type=$(echo ${DEV} | cut -f 1 -d =)
			local value=$(echo ${DEV} | cut -f 2 -d = | tr '[A-F]' '[a-f]')

			# ... in RFC#4122 format;
			# look for five hexadecimal fragments separated by minus signs.
			local fmt=$( echo "$value" | sed -e 's/[0-9a-fA-F]*//g' )
			if [ "$fmt" != '----' ]; then
				return 1
			fi
			DEV="${type}=${value}"

			# Retry with the lower cased UUID.
			DEV="$(blkid -l -t "$DEV" -o device)" || return 1
		fi
		;;
	esac
	[ -e "$DEV" ] && echo "$DEV"
}
