#!/bin/sh

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

mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev 2>/dev/null || true

echo "[rootab] initramfs started"

BOOT_PART="/dev/mmcblk0p1"
ROOT_A_PART="/dev/mmcblk0p2"
ROOT_B_PART="/dev/mmcblk0p3"

mkdir -p /bootmnt /newroot

i=0
while [ ! -b "$BOOT_PART" ] && [ "$i" -lt 100 ]; do
	sleep 0.1
	i=$((i + 1))
done

mount -t vfat "$BOOT_PART" /bootmnt || {
	echo "[rootab] ERROR: cannot mount /boot"
	exec sh
}

boot_root="$ROOT_A_PART"

if [ -f /bootmnt/rollback.flag ]; then
	echo "[rootab] rollback.flag exists"

	if [ -f /bootmnt/pending-root ] && [ -f /bootmnt/previous-root ]; then
		pending="$(cat /bootmnt/pending-root)"
		previous="$(cat /bootmnt/previous-root)"

		echo "[rootab] pending root was: $pending"
		echo "[rootab] rolling back to: $previous"

		echo "$pending" > /bootmnt/last-failed-root
		rm -f /bootmnt/pending-root
		rm -f /bootmnt/rollback.flag

		boot_root="$previous"
	else
		echo "[rootab] rollback.flag present but status files missing"
		boot_root="$ROOT_A_PART"
	fi
elif [ -f /bootmnt/pending-root ]; then
	boot_root="$(cat /bootmnt/pending-root)"
	echo "[rootab] booting pending root: $boot_root"
else
	echo "[rootab] no pending-root, defaulting to rootA"
	boot_root="$ROOT_A_PART"
fi

case "$boot_root" in
	"$ROOT_A_PART"|"$ROOT_B_PART")
		;;
	*)
		echo "[rootab] invalid root: $boot_root"
		boot_root="$ROOT_A_PART"
		;;
esac

echo "[rootab] mounting root: $boot_root"

mount -t btrfs -o rw "$boot_root" /newroot || {
	echo "[rootab] ERROR: cannot mount $boot_root"
	exec sh
}

umount /bootmnt
umount /proc
umount /sys

exec switch_root /newroot /sbin/init
