#!/bin/bash
# Armbian: snapshots of a btrfs root, made with snapper. The apt hook of the
# snapper package takes a snapshot before and after each package change.
set -euo pipefail

usage() {
	cat >&2 << 'EOT'
Usage: armbian-snapshot list
       armbian-snapshot create [description]
       armbian-snapshot restore [--with-home] [number]

restore makes a snapshot the root again. Without a number, it restores the
snapshot that is booted: GRUB menu "Armbian snapshots", or without GRUB the
S key at boot. /home stays as it is now. --with-home restores /home from the
snapshot too. Reboot after it.
EOT
	exit 1
}

cmd="${1:-}"
case "$cmd" in
list | create | restore) ;;
*) usage ;;
esac

if [[ $EUID -ne 0 ]]; then
	command -v sudo > /dev/null && exec sudo -- "$0" "$@"
	echo "Run armbian-snapshot as root." >&2
	exit 1
fi

if [[ ! -e /etc/snapper/configs/root ]]; then
	echo "There are no snapshots of /. They need a btrfs root." >&2
	if [[ $(findmnt -n -o FSTYPE /) == btrfs ]]; then
		echo "To set them up, run: systemctl start armbian-snapshots.service" >&2
	fi
	exit 1
fi

# A snapshot boot: the root is a RAM overlay over the snapshot. Its
# /.snapshots is empty: the snapshots are in the normal root, next to it.
booted="$(cat /run/armbian-snapshot/number 2> /dev/null || true)"

# The snapshots of the normal root, read from the top level of the btrfs
# volume (read-only). The booted one has a *.
list_from_top() {
	# top is global: the EXIT trap needs it.
	local lower=/run/armbian-snapshot/lower dev base info num date type desc mark
	dev="$(findmnt -n -o SOURCE "$lower" | sed 's/\[.*//')"
	base="$(findmnt -n -o FSROOT "$lower")"
	base="${base#/}"
	base="${base%%/*}"
	top="$(mktemp -d)"
	trap 'umount "$top" 2> /dev/null || true; rmdir "$top"' EXIT
	mount -o ro,subvolid=5 "$dev" "$top"
	printf '  %4s  %-6s  %-19s  %s\n' "#" Type Date Description
	for info in "$top/$base"/.snapshots/*/info.xml; do
		[[ -f $info ]] || continue
		num="$(sed -n 's:.*<num>\([0-9]*\)</num>.*:\1:p' "$info")"
		date="$(sed -n 's:.*<date>\(.*\)</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" "$type" "$date" "$desc"
	done | sort -n | while IFS=$'\t' read -r num type date desc; do
		mark=" "
		[[ $num == "$booted" ]] && mark="*"
		printf '%s %4s  %-6s  %-19s  %s\n' "$mark" "$num" "$type" "$date" "$desc"
	done
	echo "* runs now. Times in UTC."
}

shift
case "$cmd" in
list)
	if [[ -n $booted ]]; then
		list_from_top
	else
		snapper -c root list
	fi
	;;
create)
	if [[ -n $booted ]]; then
		echo "This system runs from snapshot $booted: a snapshot of it is lost at reboot." >&2
		exit 1
	fi
	# Snapper 0.10.4 (bookworm) has no plugin event for the boot copy.
	/usr/lib/armbian-snapshots/boot-copy
	snapper -c root create -c number -p -d "${*:-armbian-snapshot}" | sed 's/^/Snapshot /'
	;;
restore) exec /usr/lib/armbian-snapshots/restore "$@" ;;
esac
