#!/bin/sh
# Armbian: a boot partition is not in the snapshots of the root. Copy it
# into the root before a snapshot, so that each snapshot has its own kernel.
# The boot partition is /boot, or else /boot/firmware: a Raspberry Pi keeps
# /boot in the root, but its firmware loads the kernel from /boot/firmware.
# armbian-snapshot restore copies it back. Callers: the snapper plugin
# 40-armbian-boot (snapper 0.10.5 and newer). For snapper 0.10.4: the apt
# hook 79armbian-snapshots, armbian-snapshot create and a drop-in for
# snapper-boot.service.
# rsync writes only the changed files: btrfs shares the others with the
# older snapshots.
# Not on a snapshot boot: its root is a RAM overlay.
[ -e /run/armbian-snapshot/number ] && exit 0
grep -q 'armbian\.snapshot=' /proc/cmdline && exit 0
# The mark <copy>.ok says that the copy is complete and current. Remove the
# marks first: a copy that this run does not make, for example with the boot
# partition not mounted, is not current. Restore uses only a marked copy.
# Restore trusts only a regular file, so a directory there is no mark. A mark
# that stays (immutable file) must not mark an old copy: remove the copy, or
# if that fails too, veto it with <copy>.stale. Handle every mark, then make
# no new copy.
stuck=
for mark in /var/lib/armbian-snapshots/boot.ok /var/lib/armbian-snapshots/boot-firmware.ok; do
	copy="${mark%.ok}"
	rm -f "$mark" 2> /dev/null || true
	if [ -f "$mark" ]; then
		rm -rf "$copy" 2> /dev/null || touch "$copy.stale"
		logger -t armbian-snapshots "cannot remove $mark: no new copy of the boot partition"
		stuck=yes
		continue
	fi
	rm -f "$copy.stale"
done
[ -z "$stuck" ] || exit 0
if mountpoint -q /boot; then
	part=/boot
	dst=/var/lib/armbian-snapshots/boot
elif mountpoint -q /boot/firmware; then
	part=/boot/firmware
	dst=/var/lib/armbian-snapshots/boot-firmware
else
	exit 0
fi
mkdir -p "$dst"
# --modify-window: vfat keeps the time in steps of 2 seconds.
if rsync -rlt --delete --modify-window=1 "$part/" "$dst/"; then
	touch "$dst.ok"
else
	logger -t armbian-snapshots "copy of $part into the root failed"
fi
exit 0
