1#!/bin/sh
2#
3# $FreeBSD$
4#
5
6# Print newline-separated list of devices available for mounting.
7# If there is a filesystem label - use it, otherwise use device name.
8print_available() {
9	local _fstype _fstype_and_label _label _p
10
11	for _p in ${providers}; do
12		_fstype_and_label="$(fstyp -l "/dev/${_p}" 2> /dev/null)"
13		if [ $? -ne 0 ]; then
14			# Ignore devices for which we were unable
15			# to determine filesystem type.
16			continue
17		fi
18
19		_fstype="${_fstype_and_label%% *}"
20		if [ "${_fstype}" != "${_fstype_and_label}" ]; then
21			_label="${_fstype_and_label#* }"
22			echo "${_label}"
23			continue
24		fi
25
26		echo "${_p}"
27	done
28}
29
30# Print a single map entry.
31print_one() {
32	local _fstype _fstype_and_label _label _key _p
33
34	_key="$1"
35
36	_fstype="$(fstyp "/dev/${_key}" 2> /dev/null)"
37	if [ $? -eq 0 ]; then
38		echo "-fstype=${_fstype},nosuid	:/dev/${_key}" 
39		return
40	fi
41
42	for _p in ${providers}; do
43		_fstype_and_label="$(fstyp -l "/dev/${_p}" 2> /dev/null)"
44		if [ $? -ne 0 ]; then
45			# Ignore devices for which we were unable
46			# to determine filesystem type.
47			continue
48		fi
49
50		_fstype="${_fstype_and_label%% *}"
51		if [ "${_fstype}" = "${_fstype_and_label}" ]; then
52			# No label, try another device.
53			continue
54		fi
55
56		_label="${_fstype_and_label#* }"
57		if [ "${_label}" != "${_key}" ]; then
58			# Labels don't match, try another device.
59			continue
60		fi
61
62		echo "-fstype=${_fstype},nosuid	:/dev/${_p}" 
63	done
64
65	# No matching device - don't print anything, autofs will handle it.
66}
67
68# Obtain a list of (geom-provider-name, access-count) pairs, turning this:
69#
70# z0xfffff80005085d00 [shape=hexagon,label="ada0\nr2w2e3\nerr#0\nsector=512\nstripe=0"];
71#
72# Into this:
73#
74# ada0 r2w2e3
75#
76# XXX: It would be easier to use kern.geom.conftxt instead, but it lacks
77#      access counts.
78pairs=$(sysctl kern.geom.confdot | sed -n 's/^.*hexagon,label="\([^\]*\)\\n\([^\]*\).*/\1 \2/p')
79
80# Obtain a list of GEOM providers that are not already open - not mounted,
81# and without other GEOM class, such as gpart, attached.  In other words,
82# grep for "r0w0e0".  Skip providers with names containing slashes; we're
83# not interested in geom_label(4) creations.
84providers=$(echo "$pairs" | awk '$2 == "r0w0e0" && $1 !~ /\// { print $1 }')
85
86if [ $# -eq 0 ]; then
87	print_available
88	exit 0
89fi
90
91print_one "$1"
92exit 0
93
94