#!/bin/sh
# Copyright (C) 2011 O.S. Systems Software LTDA.
# Licensed on MIT

rootfs_enabled() {
	return 0
}

rootfs_run() {
        if [ -z "$ROOTFS_DIR" ]; then
		return
        fi
	C=0
	delay=${bootparam_rootdelay:-1}
	timeout=${bootparam_roottimeout:-5}
	while ! mountpoint -q $ROOTFS_DIR; do
		if [ $(( $C * $delay )) -gt $timeout ]; then
			fatal "root '$bootparam_root' doesn't exist or does not contain a /dev."
		fi

		if [ -n "$bootparam_root" ]; then
			debug "No e2fs compatible filesystem has been mounted, mounting $bootparam_root..."

			case "$bootparam_root" in
				UUID=*)
					bootparam_root="/dev/disk/by-uuid/${bootparam_root#UUID=}"
					;;
				PARTUUID=*)
					bootparam_root="/dev/disk/by-partuuid/${bootparam_root#PARTUUID=}"
					;;
				PARTLABEL=*)
					bootparam_root="/dev/disk/by-partlabel/${bootparam_root#PARTLABEL=}"
					;;
				LABEL=*)
					bootparam_root="/dev/disk/by-label/${bootparam_root#LABEL=}"
					;;
				ubi[0-9]*:*)
					ubi_prefix=${bootparam_root%%:*}
					ubi_digits=${ubi_prefix#ubi}
					case "$ubi_digits" in
						''|*[!0-9]*) ;;
						*) bootparam_rootfstype="ubifs" ;;
					esac
					;;
			esac

			if [ -e "$bootparam_root" ] || [ -n "$bootparam_rootfstype" ]; then
				flags=""
				if [ -n "$bootparam_ro" ] && ! echo "$bootparam_rootflags" | grep -w -q "ro"; then
					if [  -n "$bootparam_rootflags" ]; then
						bootparam_rootflags="$bootparam_rootflags,"
					fi
					bootparam_rootflags="${bootparam_rootflags}ro"
				fi
				if [ -n "$bootparam_rootflags" ]; then
					flags="$flags -o$bootparam_rootflags"
				fi
				if [ -n "$bootparam_rootfstype" ]; then
					flags="$flags -t$bootparam_rootfstype"
				fi
				debug "mount $flags $bootparam_root $ROOTFS_DIR"
				mount $flags $bootparam_root $ROOTFS_DIR
				if mountpoint -q $ROOTFS_DIR; then
					break
				else
					# It is unlikely to change, but keep trying anyway.
					# Perhaps we pick a different device next time.
					umount $ROOTFS_DIR
				fi
			fi
		fi
		debug "Sleeping for $delay second(s) to wait for root to settle..."
		sleep $delay
		C=$(( $C + 1 ))
	done
}
