# Local filesystem mounting

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

		# Default delay is 180s
		slumber=${ROOTDELAY:-180}
		usplash_write "TIMEOUT ${slumber}"

		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 ||:
		fi
		usplash_write "TIMEOUT 15"
	fi
}

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

	if [ ! -e /sys/power/resume ]; then
		log_warning_msg "Kernel does not support resume - doing normal boot"
		return 0
	fi

	[ -e "${resume}" ] || wait_for_device "$resume" "Waiting for resume device"

	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

	if [ ! -e /sys/power/suspend2/do_resume ]; then
		log_warning_msg "Kernel does not support resume"
		return 0
	fi

	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
	[ -z "$ROOTFSTYPE" ] && eval $(fstype "$ROOT") || FSTYPE="$ROOTFSTYPE"
	[ "$FSTYPE" = "unknown" -a -x /lib/udev/vol_id ] && FSTYPE=$(/lib/udev/vol_id -t $ROOT)
	[ -z "$FSTYPE" ] && FSTYPE="auto"

	run_scripts /scripts/local-premount

	local f
	[ "x$readonly" = xy ] && f=r || f=w

	# FIXME This has no error checking
	[ "$FSTYPE" = "auto" ] || modprobe -qb $FSTYPE

	# Mount root
	if ! mount -$f -t $FSTYPE $ROOTFLAGS $ROOT $rootmnt; then
		if [ "x$FSTYPE" = "xext3" ]; then
			log_warning_msg "Trying to mount $ROOT as ext2 instead of ext3"
			modprobe -qb ext2
			mount -$f -t ext2 $ROOTFLAGS $ROOT $rootmnt
		else
			panic "Unable to mount $ROOT as $FSTYPE.  Dropping to a shell!"
		fi
	fi

	if [ -n "$ROOTSUBDIR" ]; then
		[ -d "$rootmnt/$ROOTSUBDIR" ] || panic "rootsubdir $ROOTSUBDIR does not exists"
		log_begin_msg "Changing root to rootsubdir $ROOTSUBDIR"
		mount -o move $rootmnt /loopfs
		mount -o bind /loopfs/$ROOTSUBDIR ${rootmnt}
		umount /loopfs
		log_end_msg
	fi

	run_scripts /scripts/local-bottom
}
