#!/bin/sh
# Armbian: boot a snapper snapshot of the root with a writable RAM overlay.
# GRUB snapshot entries (/etc/grub.d/42_armbian-snapshots) set
# armbian.snapshot=<number>. Without GRUB (U-Boot, Raspberry Pi), the S key
# at boot opens a menu of the snapshots: SNAPSHOT_MENU_TIMEOUT in
# /etc/default/armbian-snapshots. The kernel is the current one.
# 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

. /scripts/functions

d=/run/armbian-snapshot
n="$(sed -n 's/.*armbian\.snapshot=\([0-9]*\).*/\1/p' /proc/cmdline)"

# What the menu did, for a look after the boot: /run/armbian-snapshot/menu.log.
log() {
	mkdir -p "$d"
	echo "$(cut -d ' ' -f 1 /proc/uptime) $*" >> "$d/menu.log"
}

# The root mount: device and options.
root_mount() {
	while read -r mdev mpoint _ mopts _; do
		[ "$mpoint" = "${rootmnt}" ] && return 0
	done < /proc/mounts
	return 1
}

# Wait up to $1 seconds for the S key. Splash screen: plymouth, else the
# consoles. Set tty to the console of the key: the menu shows there. The last
# console= of the kernel command line is /dev/console, often a serial port.
s_key() {
	if plymouth --ping 2> /dev/null; then
		log "plymouth runs: waiting $1 s for S"
		plymouth display-message --text="Press S for the snapshot menu"
		# watch-keystroke prints the key. It can also end without one.
		mkdir -p "$d"
		plymouth watch-keystroke --keys="sS" > "$d/key" 2> /dev/null &
		pid=$!
		i=0
		while [ "$i" -lt "$1" ] && kill -0 "$pid" 2> /dev/null; do
			sleep 1
			i=$((i + 1))
		done
		plymouth display-message --text=""
		if kill -0 "$pid" 2> /dev/null; then
			kill "$pid" 2> /dev/null
			log "no S key"
			return 1
		fi
		key="$(cat "$d/key" 2> /dev/null)"
		rm -f "$d/key"
		case "$key" in
		s | S) ;;
		*)
			log "plymouth ended without S: '$key'"
			return 1
			;;
		esac
		# hide-splash keeps the keyboard in plymouth. deactivate frees it, but
		# leaves the screen in graphics mode: black. quit frees both. systemd
		# starts the splash again (plymouth-start.service).
		plymouth quit 2> /dev/null
		# The keyboard types into the screen.
		tty=/dev/console
		[ -c /dev/tty0 ] && tty=/dev/tty0
		log "S key: menu on $tty"
		return 0
	fi
	ttys=
	for t in $(cat /sys/class/tty/console/active 2> /dev/null); do
		[ -c "/dev/$t" ] && ttys="$ttys /dev/$t"
	done
	[ -n "$ttys" ] || ttys=/dev/console
	log "no plymouth: waiting $1 s for S on$ttys"
	mkdir -p "$d"
	rm -f "$d/key"
	for t in $ttys; do
		printf '\nPress S for the snapshot menu ... ' > "$t"
		(
			key=
			read -t "$1" -n 1 key < "$t" 2> /dev/null
			case "$key" in s | S) echo "$t" >> "$d/key" ;; esac
		) &
	done
	wait
	for t in $ttys; do printf '\n' > "$t"; done
	tty="$(sed -n 1p "$d/key" 2> /dev/null)"
	rm -f "$d/key"
	[ -n "$tty" ] || { log "no S key"; return 1; }
	log "S key: menu on $tty"
	return 0
}

# The snapshots, newest first: number, date (UTC), type, description.
list_snapshots() {
	for info in "${rootmnt}"/.snapshots/*/info.xml; do
		[ -f "$info" ] || continue
		num="$(sed -n 's:.*<num>\([0-9]*\)</num>.*:\1:p' "$info")"
		[ -n "$num" ] && [ -d "${rootmnt}/.snapshots/$num/snapshot" ] || continue
		date="$(sed -n 's|.*<date>\(.*\):[0-9]*</date>.*|\1|p' "$info")"
		type="$(sed -n 's:.*<type>\(.*\)</type>.*:\1:p' "$info")"
		desc="$(sed -n 's:.*<description>\(.*\)</description>.*:\1:p' "$info")"
		printf '%s\t%s\t%s\t%s\n' "$num" "$date" "$type" "$desc"
	done | sort -rn | sed -n '1,15p'
}

# Show the menu on the console. Print the chosen number, or nothing.
menu() {
	list="$(list_snapshots)"
	[ -n "$list" ] || return 0
	tab="$(printf '\t')"
	# Line input with echo: plymouth can leave the terminal in raw mode.
	stty sane < "$tty" 2> /dev/null
	{
		printf '\nArmbian snapshots (time in UTC):\n\n'
		printf '%s\n' "$list" | while IFS="$tab" read -r num date type desc; do
			printf '  %4s  %s  %-6s %s\n' "$num" "$date" "$type" "$desc"
		done
		printf '\nThe snapshot boots with a RAM overlay: changes are lost at reboot.\n'
		printf 'To keep it, run "armbian-snapshot restore" there. The kernel is the current one.\n'
		printf '\nNumber of the snapshot to boot, or Enter for the normal system: '
	} > "$tty"
	choice=
	read -t 60 -r choice < "$tty" 2> /dev/null
	log "input: '$choice'"
	printf '\n' > "$tty"
	case "$choice" in '' | *[!0-9]*) return 0 ;; esac
	printf '%s\n' "$list" | cut -f 1 | grep -qx "$choice" || return 0
	# For the notice in the system: the date of the snapshot (UTC).
	mkdir -p "$d"
	printf '%s\n' "$list" | while IFS="$tab" read -r num date _; do
		[ "$num" = "$choice" ] && echo "$date" > "$d/date"
	done
	echo "$choice"
}

if [ -z "$n" ]; then
	# GRUB has its own snapshot entries.
	grep -q 'BOOT_IMAGE=' /proc/cmdline && exit 0
	SNAPSHOT_MENU_TIMEOUT=2
	[ -f /conf/armbian-snapshots.conf ] && . /conf/armbian-snapshots.conf
	case "$SNAPSHOT_MENU_TIMEOUT" in '' | *[!0-9]* | 0) exit 0 ;; esac
	[ -d "${rootmnt}/.snapshots" ] || { log "no ${rootmnt}/.snapshots: no menu"; exit 0; }
	command -v sort > /dev/null || { log "no sort: no menu"; exit 0; }
	root_mount || { log "root mount not found: no menu"; exit 0; }
	subvol="$(echo "$mopts" | sed -n 's/.*subvol=\([^,]*\).*/\1/p')"
	[ -n "$subvol" ] || { log "root is not a subvolume: no menu"; exit 0; }
	s_key "$SNAPSHOT_MENU_TIMEOUT" || exit 0
	n="$(menu)"
	log "chosen: '$n'"
	[ -n "$n" ] || exit 0
	# Mount the snapshot before the root goes. cryptroot (local-bottom) marks
	# the LUKS device for deferred removal: the device goes with its last
	# mount, and a mount after that fails.
	mkdir -p "$d/lower"
	if ! mount -t btrfs -o "ro,subvol=${subvol%/}/.snapshots/$n/snapshot" "$mdev" "$d/lower"; then
		log_failure_msg "armbian-snapshot: cannot mount snapshot $n, normal boot"
		exit 0
	fi
	if ! umount "${rootmnt}"; then
		umount "$d/lower"
		log_failure_msg "armbian-snapshot: cannot unmount the root, normal boot"
		exit 0
	fi
	lower_ready=yes
	log "snapshot $n mounted"
	log_success_msg "armbian-snapshot: booting snapshot $n"
fi

# Without the overlay, boot the snapshot read-only.
read_only() {
	log_failure_msg "armbian-snapshot: $1, the snapshot stays read-only"
	[ "$lower_ready" = yes ] && mount -n -o move "$d/lower" "${rootmnt}"
	exit 0
}

# The tools in the system read the number here: restore, notice, boot-copy.
# Also for a read-only fallback below.
mkdir -p "$d"
echo "$n" > "$d/number"

modprobe overlay || read_only "no overlay module"
mkdir -p "$d/lower" "$d/rw"
mount -n -t tmpfs -o mode=0755 tmpfs "$d/rw" || read_only "no tmpfs"
mkdir -p "$d/rw/upper" "$d/rw/work"
[ "$lower_ready" = yes ] || 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 units that the GRUB entries mask (systemd.mask): mask them in the RAM
# overlay too, for a boot from the menu.
mkdir -p "${rootmnt}/etc/systemd/system"
# armbian-resize-filesystem changes the partitions and the LUKS device below.
for unit in systemd-remount-fs.service snapper-boot.service armbian-luks-rekey.service armbian-snapshots.service armbian-resize-filesystem.service; do
	ln -sf /dev/null "${rootmnt}/etc/systemd/system/$unit"
done
# 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. nofail: a boot partition that does not mount must not stop
# the snapshot boot (emergency mode). 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,nofail|' "${rootmnt}/etc/fstab" ||
		log_warning_msg "armbian-snapshot: /boot stays writable"
fi
exit 0
