#!/bin/sh
# Units provisioned before the 10-fstab fix recorded the internal rootfs_data
# as an enabled /overlay mount. sysupgrade regenerates that UUID, so the entry
# then points at a device that will never appear; block reads it as an extroot,
# waits delay_root seconds for it and falls back to the internal overlay, on
# every boot. That is ~5s of the boot on a photonicat2.
#
# A deliberately configured extroot on an external disk looks the same once the
# disk is unplugged or slow to enumerate, and deleting that would silently cost
# someone their overlay. Two guards keep this to the machine-generated case:
#
#   - a /rom mount entry must be present. Nothing but `block detect` writes one,
#     so it marks the whole file as generated rather than hand-written.
#   - the /overlay entry's own device must be absent right now.
#
# A unit whose fstab has no /rom entry keeps the stall and needs fixing by hand;
# that is the safe direction to be wrong in.

generated_by_block_detect() {
	uci show fstab 2>/dev/null | \
		grep -qE "^fstab\.@mount\[[0-9]+\]\.target='/rom'\$"
}

device_present() {
	local uuid="$1" dev="$2"

	[ -n "$dev" ] && { [ -b "$dev" ] && return 0 || return 1; }
	[ -n "$uuid" ] || return 1
	block info 2>/dev/null | grep -q "UUID=\"$uuid\""
}

generated_by_block_detect || exit 0

while :; do
	stale=""
	for section in $(uci show fstab 2>/dev/null | \
		grep -E "^fstab\.@mount\[[0-9]+\]\.target='/overlay'\$" | cut -d. -f2); do
		device_present "$(uci -q get "fstab.$section.uuid")" \
			       "$(uci -q get "fstab.$section.device")" && continue
		stale="$section"
		break
	done
	[ -n "$stale" ] || break
	uci -q delete "fstab.$stale" || break
	uci -q commit fstab
done

exit 0
