#! /bin/sh
### BEGIN INIT INFO
# Provides:          mtab
# Required-Start:
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Create initial /etc/mtab
# Description:       Creates the initial /etc/mtab containing details of
#                    filesystems mounted early during the boot sequence.
### END INIT INFO

# Script needs to be robust and continue when parts fail,
# so we're not setting the "-e" flag.
#set -e

PATH=/lib/init:/bin:/sbin

. /lib/init/functions.sh

TTYGRP=5
TTYMODE=620
if [ -f /etc/default/devpts ]
then
	. /etc/default/devpts
fi

TMPFS_SIZE=
if [ -f /etc/default/tmpfs ]
then
	. /etc/default/tmpfs
fi

umask 022

domtab ()
{
	# Directory present?
	if [ ! -d $2 ]
	then
		return
	fi

	# Not mounted?
	if ! mountpoint -q $2
	then
		return
	fi

	if [ -n "$3" ]
	then
		NAME="$3"
	else
		NAME="$1"
	fi

	# Already recorded?
	if ! grep -E -sq "^([^ ]+) +$2 +" /etc/mtab
	then
		mount -f -t $1 $OPTS $4 $NAME $2
	fi
}

do_start () {
	#
	#	If /etc/mtab is a symlink into /proc/ then we assume
	#	it is not writable.
	#
	MTAB_PATH="`readlink -f /etc/mtab || :`"
	case "$MTAB_PATH" in
		/proc/*)
			return
			;;
		/*)
			# Only update mtab if it is writable
			if ! touch $MTAB_PATH > /dev/null 2>&1
			then
				return
			fi
			;;
	esac

	if selinux_enabled && [ -x /sbin/restorecon ] && [ -r /etc/mtab ]; then
		/sbin/restorecon /etc/mtab
	fi

	if [ -n "$TMPFS_SIZE" ]
	then
		tmpfs_opt="-osize=${TMPFS_SIZE}"
	fi

	# S01mountvirtfs
	domtab proc /proc "proc"
	domtab sysfs /sys "sys"
	domtab tmpfs /var/run "varrun"
	domtab tmpfs /var/lock "varlock"
	domtab usbfs /proc/bus/usb "procbususb"

	# S01udev
	domtab tmpfs /dev "udev"

	# S02mountdevsubfs
	domtab devpts /dev/pts "devpts" -ogid=$TTYGRP,mode=$TTYMODE
	domtab tmpfs /dev/shm "devshm" $tmpfs_opt

	# S07linux-restricted-modules-common
	exec 9<&0 0</proc/mounts
	while read FDEV FDIR FTYPE FOPTS REST
	do
		case "$FDIR" in
			/lib/modules/*/volatile)
				domtab "$FTYPE" "$FDIR" "lrm"
				;;
		esac
	done
	exec 0<&9 9<&-
}

case "$1" in
    start)
        do_start
        ;;
    restart|reload|force-reload)
        echo "Error: argument '$1' not supported" >&2
        exit 3
        ;;
    stop)
        ;;
    *)
        echo "Usage: $0 start|stop" >&2
        exit 3
        ;;
esac
