#!/bin/sh

O=full
P=
D=
FIND=
USAGE=
while [ "$#" != 0 ]; do
	case "$1" in
		-k)
			echo "\
squashfs
ext2
ext3
ext4
btrfs
reiserfs
jfs
xfs
iso9660
udf
nilfs2
cramfs
ocfs2
swap
crypto_LUKS
linux_raid_member"
			exit 0
			;;
		-o)
			case "$2" in
				value|device|udev|full|export)
					O=$2
					shift
					;;
				*)
					echo "Invalid output format $2. Choose from value, device, udev, export or full"
					exit 4
					;;
			esac
			;;
		-p)
			P=1
			;;
		-L)
			FIND="LABEL=$2"
			shift
			;;
		-O)
			shift
			;;
		-U)
			FIND="UUID=$2"
			shift
			;;
		-u)
			USAGE="${USAGE:+$USAGE,}$1"
			shift
			;;
		-*)
			;;
		*)
			D="${D:+$D }$1"
			;;
	esac
	shift
done

if [ -n "$FIND" ]; then
	/sbin/findfs "$FIND"
	exit $?
fi

if [ -z "$D" -a -n "$P" ]; then
	echo "The low-level probing mode requires a device" >&2
	exit 4
fi

AddTag()
{
	local s

	case $O in
		value)
			[ -z "$S" ] && S="$2" || S="$S
$2"
			;;
		udev)
			s="ID_FS_$1=$2"
			[ -z "$S" ] && S="$s" || S="$S
$s"
			if [ "$1" = LABEL -o "$1" = UUID ]; then
				S="$S
ID_FS_${1}_ENC=$2"
				return
			fi
			;;
		export)
			s="$1=$2"
			[ -z "$S" ] && S="$s" || S="$S
$s"
			;;
		full)
			S="${S:+$S }$1=\"$2\""
			;;
	esac
	if [ -n "$P" -a "$1" = TYPE ]; then
		case "$2" in
			squashfs|ext[234]|btrfs|reiserfs|jfs|xfs|iso9660|udf|nilfs[23]|cramfs|ocfs2)
				s=filesystem
				;;
			swap)
				s=other
				;;
			crypto*)
				s=crypto
				;;
			*raid*)
				s=raid
				;;
			*)
				return 0
				;;
		esac
		AddTag USAGE "$s"
	fi
}

i=
/bin/busybox blkid $D |
while read A; do
	case $O in
		device)
			echo "${A%: *}"
			continue
			;;
		udev)
			echo -n "$i"
			S=
			;;
		export)
			echo -n "$i"
			S="DEVNAME=${A%: *}"
			;;
		full)
			if [ -z "$P" ]; then
				echo "$A"
				continue
			fi
			S="${A%: *}:"
			;;
	esac
	for a in ${A#*: }; do
		a="${a%\"}"
		AddTag "${a%=*}" "${a#*=\"}"
	done
	echo "$S"
	i="
"
done
