summaryrefslogtreecommitdiffstats
path: root/builder/modules.d/slx-dmsetup/scripts/get-partitions-by-id
blob: 2fe5ce7a3a387e30d34357857c0c0fab7ff9e97f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env bash
#
# Get all partitions with given ids (list of /dev/sdXX)
# Examples of supported ID types:
#  * MBR's type: 44
#  * GPT's UUID: 0657fd6d-a4ab-43c4-84e5-0933c84b4f4f (swap)
#  * GPT's Name: OpenSLX-ID44
#
# First argument can be a block device to limit the search to
# partitions thereof, e.g. for /dev/loop0 to look for /dev/loop0pX
#
# NOTE: for compatibility reasons, MBR's type will also
# be matched against part name 'OpenSLX-ID<id>'.
# The output will be a list of matching devices,
# sorted from largest to smallest.
get_partitions_by_id () {
	local ID dev exp target
	exp=
	# target for the scan, defaults to /dev to check everything
	target=/dev
	if [ -b "$1" ]; then
		target="$1"'*'
		shift
	fi
	# support commas and pipes to separate identifiers
	local args=$@
	set -- ${args//[,|]/ }
	while [ $# -gt 0 ]; do
		ID=$1
		shift
		[ -z "$ID" ] && continue
		# if single digit, e.g. 7, look for 0x7 and 0x07
		[[ $ID =~ ^[0-9]$ ]] && ID="0?$ID"
		if [[ $ID =~ ^[0-9]{2}$ ]]; then
			# if double digit look for MBR types and OpenSLX-ID$ID GPT labels
			exp="$exp|ID_PART_ENTRY_(NAME=OpenSLX-ID|TYPE=0x)$ID"
		elif [[ $ID =~ ^(0x[0-9]{2}|[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})$ ]]; then
			# if full MBR type (e.g. 0x44) or UUID look for TYPE
			exp="$exp|ID_PART_ENTRY_TYPE=$ID"
		else
			# something else, look for names of partitions / filesystems
			exp="$exp|ID_(PART_ENTRY_NAME|FS_LABEL)=$ID"
		fi
	done
	exp=${exp:1}
	#echo "Partition find is '$exp'" >&2
	for dev in $(find $target -type b); do
		udevadm info --name="$dev" | grep -iqE "($exp)\$" \
			&& echo "$(blockdev --getsize64 "$dev") $dev"
	done | sort -n -k1 -r | cut -d' ' -f2
}

## MAIN
if [ $# -eq 0 ]; then
	echo "$0 needs at least one argument."
	exit 1
fi

get_partitions_by_id $@