set -e

ROOTDIR=/mnt/root

log_debug()
{
	if [ "$cmdline_rdinit_debug" = yes ]; then
		echo "$@" >&2
	fi
}

try_switch_root()
{
	local init dev="$1"

	log_debug "Switching root to $dev"

	[ -n "$cmdline_init" ] && init="$cmdline_init" || init=/sbin/init

	mount "$dev" "$ROOTDIR" || return 0
	if [ ! -x "$ROOTDIR/$init" ]; then
		umount "$ROOTDIR"
		return 0
	fi

	exec switch_root -c /dev/console "$ROOTDIR" "$init"
}

try_switch_root_mdev()
{
	MDEVS=$(ls /sys/block/ | grep -e '^md') || return 0
	for mdev in $MDEVS; do
		try_switch_root /dev/$mdev
	done
}

try_switch_root_sdev()
{
	SDEVS=$(ls /sys/block/ | grep -e '^sd') || return 0
	for sdev in $SDEVS; do
		SDPARTS=$(ls /sys/block/$sdev/ | grep -e "^$sdev")
		if [ $? -ne 0 ]; then
			try_switch_root /dev/$sdev
			continue
		fi
		for sdpart in $SDPARTS; do
			try_switch_root /dev/$sdpart
		done
	done
}

mkdir -p "$ROOTDIR"

if [ -x /sbin/mdadm ]; then
	mdadm -E -s > /etc/mdadm.conf
	[ -s /etc/mdadm.conf ] && mdadm -A -s
fi

# Ignore 'root' command line argument when provided by a LaCie stock U-Boot.
if [ -z "$cmdline_productType" ] && [ -n "$cmdline_root" ]; then
	try_switch_root "$cmdline_root"
else
	try_switch_root_mdev
	try_switch_root_sdev
fi

echo "Fail to switch root"
