#!/bin/bash
### BEGIN INIT INFO
# Provides:            fstab
# Required-Start:      cmdline
# Should-Start:
# Required-Stop:
# Should-Stop:
# Default-Start:       3 4 5
# Default-Stop:
# Short-Description:   Creates /etc/fstab.
# Description:         Creates /etc/fstab.
### END INIT INFO

[ "$1" = start ] || exit 0

. /.initrd/initenv
. /etc/init.d/functions

convert_dev()
{
	local retval dev value major minor
	retval="$1"
	dev="$2"

	case "$dev" in
		[0-9]*:[0-9]*)
			value="/dev/block/$dev"
			;;
		[0-9A-Fa-f]*)
			if (_=$(( 0x$dev ))) 2>/dev/null; then
				value=$(( 0x$dev ))
				major=$(( $value / 256 ))
				minor=$(( $value % 256 ))
				value="/dev/block/$major:$minor"
			else
				value="$dev"
			fi
			;;
		*)
			value="$dev"
			;;
	esac
	eval "$retval=\"\$value\""
}

gen_fstab()
{
	local i=1 n dev path str s0 ndev roflags
	local have_sys='' have_run=''

	for conf in /etc/fstab /etc/fstab.d/*.conf; do
		[ -s "$conf" ] ||
			continue

		while read -r dev path str; do
			[ -n "${dev##\#*}" ] && [ -z "${path##/*}" ] ||
				continue
			n=$i
			case "$path" in
				/)
					n=0
					path=
					;;
				/proc|/proc/*|/dev|/dev/*|/.initrd|/.initrd/*)
					continue
					;;
				/sys)
					have_sys=1
					;;
				/run)
					have_run=1
					;;
				*)
					i=$(($i+1))
					;;
			esac

			convert_dev ndev "$dev"

			eval "local s$n=\"\$ndev \$rootmnt\$path \$str\""
		done < "$conf"
	done

	if [ -n "${ROOT-}" ]; then
		convert_dev ndev "$ROOT"
		ROOTFLAGS="${ROOTFLAGS:-defaults}"

		roflag=rw
		[ -z "$READONLY" ] || roflag=ro

		ROOTFLAGS="$ROOTFLAGS,$roflag"

		if [ -z "${ndev##SOURCE=*}" ]; then
			ndev="${ndev#SOURCE=}"
			ROOTFLAGS="$ROOTFLAGS,x-initrd-mount-source"
		fi

		s0="$ndev $rootmnt ${ROOTFSTYPE:-auto} $ROOTFLAGS 1 1"
	fi

	if [ -z "${s0-}" ]; then
		[ -z "${DEBUG-}" ] || echo "Root device unspecified." >&2
	fi

	if [ -z "$have_sys" ]; then
		eval "s$i=\"sysfs /sys sysfs nodev,noexec,nosuid 0 0\""
		i=$(($i+1))
	fi

	if [ -z "$have_run" ]; then
		eval "s$i=\"runfs /run tmpfs mode=755 0 0\""
		i=$(($i+1))
	fi

	if modprobe -n efivarfs 2>/dev/null; then
		eval "s$i=\"efivarfs /sys/firmware/efi/efivars efivarfs rw,nosuid,nodev,noexec,relatime 0 0\""
		i=$(($i+1))
	fi

	n=0
	while [ $n -lt $i ]; do
		eval "printf '%s\n' \"\$s$n\""
		n=$(($n+1))
	done > /etc/fstab
}

action_shell 'Creating /etc/fstab:' gen_fstab
