# Local filesystem mounting			-*- shell-script -*-

# wait_for_device <filename> <text>
wait_for_device ()
{
	if [ ! -e "$1" ]; then
		log_begin_msg "$2"

		# Default delay is 180s
		if [ -z "${ROOTDELAY}" ]; then
			slumber=180
		else
			slumber=${ROOTDELAY}
		fi
		if [ -x /sbin/usplash_write ]; then
			/sbin/usplash_write "TIMEOUT ${slumber}" || true
		fi

		slumber=$(( ${slumber} * 10 ))
		while [ ${slumber} -gt 0 ] && [ ! -e "${ROOT}" ]; do
			/bin/sleep 0.1
			slumber=$(( ${slumber} - 1 ))
		done

		if [ ${slumber} -gt 0 ]; then
			log_end_msg 0
		else
			log_end_msg 1 || true
		fi
		if [ -x /sbin/usplash_write ]; then
			/sbin/usplash_write "TIMEOUT 15" || true
		fi
	fi
}

try_to_resume ()
{
	[ -n "$resume" ] || return 0

	[ -e /sys/power/resume ] || {
		log_warning_msg "Kernel does not support resume - doing normal boot"
		return 0
	}

	if [ ! -e "${resume}" ]; then
		wait_for_device "$resume" "Waiting for resume device"
	fi

	if [ -e "$resume" ]; then
		# hardcode path, uswsusp ships an resume binary too
		/bin/resume "$resume"
	else
		log_warning_msg "Resume device $resume not found - doing normal boot"
	fi
}

try_to_resume2 ()
{
	[ -n "$resume2" ] || return 0

	[ -e /sys/power/suspend2/do_resume ] || {
		log_warning_msg "Kernel does not support resume"
		return 0
	}

	echo > /sys/power/suspend2/do_resume
}

# Parameter: Where to mount the filesystem
mountroot ()
{
	run_scripts /scripts/local-top

	# Try to resume before touching the root device
	try_to_resume
	try_to_resume2

	# If the root device hasn't shown up yet, give it a little while
	# to deal with removable devices
	wait_for_device "$ROOT" "Waiting for root file system"

	# We've given up, but we'll let the user fix matters if they can
	while [ ! -e "${ROOT}" ]; do
		echo "	Check root= bootarg cat /proc/cmdline"
		echo "	or missing modules, devices: cat /proc/modules ls /dev"
		panic "ALERT!  ${ROOT} does not exist.  Dropping to a shell!"
	done

	# Get the root filesystem type if not set
	if [ -z "${ROOTFSTYPE}" ]; then
		eval $(fstype < ${ROOT})
	else
		FSTYPE=${ROOTFSTYPE}
	fi
	if [ "$FSTYPE" = "unknown" ] && [ -x /lib/udev/vol_id ]; then
		FSTYPE=$(/lib/udev/vol_id -t ${ROOT})
		[ -z "$FSTYPE" ] && FSTYPE="unknown"
	fi

	run_scripts /scripts/local-premount

	if [ ${readonly} = y ]; then
		roflag=-r
	else
		roflag=-w
	fi

	# FIXME This has no error checking
	modprobe -qb ${FSTYPE}

	# Mount root
	mount ${roflag} -t ${FSTYPE} ${ROOTFLAGS} ${ROOT} ${rootmnt} || {
		[ "${FSTYPE}" = "ext3" ] && {
			log_warning_msg "Trying to mount $ROOT as ext2 instead of ext3"
			modprobe -qb ext2
			mount ${roflag} -t ext2 ${ROOTFLAGS} ${ROOT} ${rootmnt}
		}
	} ||
		panic "Unable to mount $ROOT as $FSTYPE.  Dropping to a shell!"

	run_scripts /scripts/local-bottom
}
