#!/bin/sh -efu

. shell-error
. shell-args

TEST=

show_help() {
	local rc="${1:-0}"
	cat <<EOF

$PROG - mount a file system via fstab in specifed mountpoint

Usage: $PROG [options] <fstab> <mount-point>

Options:
   --dry-run
   -q, --quiet      Try to be more quiet.
   -v, --verbose    Print a message for each action.
   -V, --version    print program version and exit.
   -h, --help       Show this message.

EOF
	exit "$rc"
}

workdir=
exit_handler() {
	local rc=$?
	trap - EXIT
	[ ! -d "$workdir" ] || rm -rf -- "$workdir"
	exit $rc
}

TEMP=`getopt -n $PROG -o $getopt_common_opts -l dry-run,$getopt_common_longopts -- "$@"` || show_usage
eval set -- "$TEMP"
while :; do
	case "$1" in
		--dry-run) TEST=message
			;;
		--) shift; break
			;;
		*) parse_common_option "$1"
			;;
	esac
	shift
done

[ "$#" -eq 2 ] || show_usage
fstab="`readlink -ev "$1"`"
dstdir="`readlink -ev "$2"`"

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

sed -e '\,[[:space:]]*#,d' \
    -e '\,^[[:space:]]*[^[:space:]]\+[[:space:]]\+/,!d' \
    -e 's/[[:space:]]\+/	/g' "$fstab" |
    sort -k2,2 -so "$workdir/fstab"

while read dev mpoint fstype opts dummy; do
	# ignore noauto for /boot and /boot/efi
	if [ "$mpoint" = /boot ] || [ "$mpoint" = /boot/efi ]; then
		opts=${opts//noauto}
	fi

	if printf %s "$opts" |grep -qs '\<noauto\>'; then
		continue
	fi

	case "$fstype" in
		ext2|ext3|ext4|reiserfs|xfs|jfs|btrfs)
			modprobe -b "$fstype"
			;;
		*)
			[ "$mpoint" = "/boot/efi" ] || continue
			;;
	esac

	# avoid filesystem journal rollback when investigating
	if grep -wqs forensic /proc/cmdline; then
		opts="${opts:+$opts,}ro,loop,noexec"
	fi

	cmd="mount -t '$fstype' -o '$opts'"

	case "$dev" in
		LABEL=*) cmd="$cmd -L ${dev#LABEL=}" ;;
		UUID=*)  cmd="$cmd -U ${dev#UUID=}"  ;;
		*)       cmd="$cmd $dev" ;;
	esac

	$TEST mkdir -p -- "$dstdir$mpoint"
	$TEST eval $cmd "$dstdir$mpoint"

done < "$workdir/fstab"
