#! /bin/sh

ldisk=$1
if [ -z "$ldisk" ]; then
	echo "Usage: ${0##*/} linux_disk_name [orig_bsddisk_name]"
	exit 1
fi
bsddisk=$2

#
# Figure out the freebsd device name.
#
# The mapping is ambiguous for Linux "sd" since it could map to a lot
# of different BSD names (e.g., "da", "ada", various raid controllers).
# However, it is almost always the case that "nvme" is "nvd" and "sd" is "da".
# If we have the original BSD disk name, we can use that to disambiguate the
# "sd" case.
#
case $ldisk in
    nvme*)
	dunit=`echo $ldisk | sed -e 's/nvme\([0-9][0-9]*\)n1/\1/'`
	dtype="nvd"
	if [ -n "$bsddisk" ]; then
	    case $bsddisk in
	    nda*)
		dtype="nda"
		;;
	    esac
	fi
	;;
    # XXX we only handle the first 26 units
    sd[a-z])
	# XXX and we only handle the most common names
	dtype="da"
	if [ -n "$bsddisk" ]; then
	    case $bsddisk in
	    ada*)
		dtype="ada"
		;;
	    da*)
		dtype="da"
		;;
	    esac
	fi
	dlet=`echo $ldisk | sed -e 's/sd\([a-z]\)/\1/'`
	case $dlet in
	    [a-j])
		dunit=`echo $dlet | sed -e 'y/abcdefghij/0123456789/'`
		;;
	    [k-t])
		dunit=`echo $dlet | sed -e 'y/klmnopqrst/0123456789/'`
		dunit=`expr $dunit \+ 10`
		;;
	    [u-z])
		dunit=`echo $dlet | sed -e 'y/uvwxyz/012345/'`
		dunit=`expr $dunit \+ 20`
		;;
	esac
	;;
    *)
	dtype="unknown"
	dunit=0
	;;
esac

if [ "$dtype" = "unknown" ]; then
    echo $ldisk
else
    echo "$dtype$dunit"
fi
