#!/bin/sh -efu

. shell-error

## Volume manager specific functions

fstype() {
	[ "$#" -eq 1 -a -n "$1" ] || return 1
	blkid -o value -s TYPE "$1"|grep -v swap
}

volumes() {
	blkid -o device|grep -v loop
}

## Functions

usage() {
	echo "Usage: $PROG [--help|--list-only|<outdir>]" >&2
	exit 1
}

workdir=
exit_handler() {
	local rc=$?
	trap - EXIT
	if cut -d' ' -f2 /proc/mounts |fgrep -xqs "$workdir"; then
		umount -l "$workdir"
	fi
	[ ! -d "$workdir" ] || rm -rf -- "$workdir"
	exit $rc
}

listonly=
outdir=
i=0
fstab_list() {
	local v fs fslist success
	for v in `volumes`; do
		fslist="`fstype "$v"`" && [ -n "$fslist" ] || continue

		success=
		for fs in $fslist; do
			modprobe -b $fs ||:
			mount -t "$fs" -oro "$v" "$workdir" >/dev/null 2>&1 && success=1 ||:
		done

		[ -n "$success" ] || continue

		if [ ! -f "$workdir/etc/fstab" ]; then
			umount -l "$workdir"
			continue
		fi

		i="$(($i+1))"
		[ -z "$listonly" ] &&
			cp -- "$workdir/etc/fstab" "$outdir/fstab.$i" ||
			echo "File /etc/fstab found on volume '$v'"
		umount -l "$workdir"
	done
}

[ "$#" -eq 1 ] || usage

if [ "$1" = "--list-only" ]; then
	listonly=1
elif [ "$1" = "--help" ]; then
	usage
else
	outdir="`readlink -ev "$1"`"
fi

trap exit_handler HUP PIPE INT QUIT TERM EXIT
workdir="`mktemp -dt "$PROG.XXXXXXXXXX"`"
fstab_list

[ "$i" -gt 0 ] && rc=0 || rc=1
exit $rc
