#!/bin/sh
# chkconfig: 2345 02 98
### BEGIN INIT INFO
# Provides:          mount local_fs
# Required-Start:    
# Required-Stop:     
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start mount at boot time
# Description:       Enable service provided by mount.
# X-Start-Before:    
# X-Stop-After:      
# X-Timesys-Start-Number:  02
# X-Timesys-Stop-Number:  98
### END INIT INFO

export PATH=/bin:/sbin:/usr/bin:/usr/sbin

ROOTDEV=

find_root_dev()
{
	# check kernel command line first
	for part in $(dmesg | grep 'command line:' | grep root=)
	do
		case "$part" in
			root=*) ROOTDEV=${part/root=/} ;;
		esac
	done

	test -n "$ROOTDEV" && return

	# otherwise hope it is in /etc/mtab
	while read fs mnt type opts dump pass junk
	do
		case "$mnt" in
		/) ROOTDEV=$fs; ;;
		esac
	done < /etc/fstab

	test -n "$ROOTDEV" && return
}

check_root_dev()
{
	find_root_dev
	test -z "$ROOTDEV" && return

	# cannot check rw mounted rfs
	READWRITE=no
	if touch /.tstwrt 2>/dev/null; then
		rm -f /.tstwrt
		return
	fi

	# need fsck
	test -z "$(which fsck)" && return

	# only check ide/scsi/usb/sd devices
	CANFSCK=
	case "$ROOTDEV" in
		/dev/mtd*) ;; 
		/dev/mmcblk[0-9]*|/dev/hd[a-z]*|/dev/sd[a-z]*)
			CANFSCK=yes
		;;
	esac;

	test -n "$CANFSCK" || return

  # fsck will fail if it doesn't have the filesystem
  # specific fsck utility
	fsck -N $ROOTDEV >/dev/null 2>&1 || return

	fsck -C -a $ROOTDEV
	fsckstat=$?

	if [ $fsckstat -ge 2 ]; then
		if [ $fsckstat -ge 4 ]; then
			echo "An error occurred during fsck... dropping to admin shell..."
			sulogin
		else
			echo "The filesystem was modified... rebooting"
		fi
		reboot
	fi

}

case "$1" in
	start)
		mount -t proc -n proc /proc 2>/dev/null
		mount -t sysfs -n sysfs /sys  2>/dev/null

		check_root_dev
		mount -o remount,rw /

		if [ ! -d /dev/shm ]; then mkdir -p /dev/shm ;fi
		if [ ! -d /dev/pts ]; then mkdir -p /dev/pts ;fi

		fsck -C -R -A -a
		mount -a -t nonfs,nosmbfs,nocifs,nonfs4
		swapon -a

		dmesg 2>/dev/null > /var/log/dmesg 
		touch /var/log/wtmp 2>/dev/null
	;;
	*)
	;;
esac

