#!/bin/sh
# Set up snapper for a Das OS root file system on Btrfs.
#
# Expects the layout created by the installer: the root in subvolume @ and
# snapshots in subvolume @snapshots mounted at /.snapshots, which is what
# snapper-rollback needs. Safe to run again.
set -eu

msg() { echo "das-snapper-setup: $*"; }

if [ "$(id -u)" -ne 0 ]; then
	msg "must be run as root" >&2
	exit 1
fi
if [ "$(findmnt -no FSTYPE /)" != btrfs ]; then
	msg "the root file system is not Btrfs, nothing to do"
	exit 0
fi
if [ "$(findmnt -no FSTYPE /.snapshots 2>/dev/null)" != btrfs ]; then
	msg "/.snapshots is not a mounted Btrfs subvolume" >&2
	exit 1
fi

if [ ! -e /etc/snapper/configs/root ]; then
	install -m 640 /usr/share/das/snapper/root /etc/snapper/configs/root
	msg "created /etc/snapper/configs/root"
fi
if ! grep -q '^SNAPPER_CONFIGS=".*\broot\b' /etc/conf.d/snapper; then
	sed -i 's/^SNAPPER_CONFIGS=.*/SNAPPER_CONFIGS="root"/' /etc/conf.d/snapper
fi
chmod 750 /.snapshots
chgrp wheel /.snapshots

# snapper-rollback mounts the top-level subvolume from this device.
dev=$(findmnt -no SOURCE / | sed 's/\[.*\]$//')
uuid=$(blkid -s UUID -o value "$dev")
sed -i "s|^#\?\s*dev = .*|dev = /dev/disk/by-uuid/$uuid|" /etc/snapper-rollback.conf

# Name the GRUB submenu that grub-btrfs adds
cfg=/etc/default/grub-btrfs/config
if [ -f "$cfg" ] && ! grep -q '^GRUB_BTRFS_SUBMENUNAME=' "$cfg"; then
	echo 'GRUB_BTRFS_SUBMENUNAME="Das OS snapshots"' >>"$cfg"
fi

# Hourly snapshots come from cron, and grub-btrfs adds them to the boot menu.
for sv in cronie grub-btrfs; do
	ln -sfn "/etc/sv/$sv" "/etc/runit/runsvdir/default/$sv"
done
msg "snapshots are enabled"
