#!/bin/sh
# Armbian: boot a snapper snapshot of the root with a writable RAM overlay.
# The GRUB snapshot entries (/etc/grub.d/42_armbian-snapshots) set
# armbian.snapshot=<number>.
# After cryptroot: it finds the LUKS device below the root mount. Below an
# overlay it finds none and gives a warning.
PREREQ="cryptroot"
prereqs() { echo "$PREREQ"; }
case "$1" in
prereqs)
	prereqs
	exit 0
	;;
esac

grep -q 'armbian\.snapshot=' /proc/cmdline || exit 0
. /scripts/functions

d=/run/armbian-snapshot
if ! modprobe overlay; then
	log_failure_msg "armbian-snapshot: no overlay module, the snapshot stays read-only"
	exit 0
fi
mkdir -p "$d/lower" "$d/rw"
if ! mount -n -t tmpfs -o mode=0755 tmpfs "$d/rw"; then
	log_failure_msg "armbian-snapshot: no tmpfs, the snapshot stays read-only"
	exit 0
fi
mkdir -p "$d/rw/upper" "$d/rw/work"
mount -n -o move "${rootmnt}" "$d/lower"
if ! mount -n -t overlay -o "lowerdir=$d/lower,upperdir=$d/rw/upper,workdir=$d/rw/work" overlay "${rootmnt}"; then
	log_failure_msg "armbian-snapshot: overlay failed, the snapshot stays read-only"
	mount -n -o move "$d/lower" "${rootmnt}"
	exit 0
fi
# The snapshot shares /boot and /boot/* partitions with the system. Mount them
# read-only: a kernel or initramfs update here breaks the next normal boot. Below
# the overlay, cryptsetup finds no LUKS device, so a new initrd does not unlock an
# encrypted root. Only the fstab in the RAM overlay changes.
if [ -f "${rootmnt}/etc/fstab" ]; then
	sed -i -E 's|^([[:space:]]*[^#[:space:]]+[[:space:]]+/boot(/[^[:space:]]*)?[[:space:]]+[^[:space:]]+[[:space:]]+)([^[:space:]]+)|\1\3,ro|' "${rootmnt}/etc/fstab" ||
		log_warning_msg "armbian-snapshot: /boot stays writable"
fi
exit 0
