#!/bin/bash

DEFAULT="$1"
LASTBOOT="lastboot"

ROOT_FS=$(findmnt -no SOURCE /)
BASE="${ROOT_FS%/*}"

EFI_DIR="/efi"

# default UKI name used by kernel-install
UKI_NAME="$(cat /etc/machine-id)-$(uname -r).efi"

if [ "$ROOT_FS" = "$BASE/$DEFAULT" ]; then
  echo "sucessfully booted to $BASE/$DEFAULT, preparing lastboot"

  # destroy the old lastboot file system and children
  zfs destroy -Rv "$BASE/$DEFAULT@lastboot"

  # make a new lastboot file system
  zfs snap -r "$BASE/$DEFAULT@lastboot"

  for OLDFS in $(zfs list -rHo name -t filesystem "$BASE/$DEFAULT"); do
    NEWFS=$(sed "s|^$BASE/$DEFAULT|$BASE/$LASTBOOT-$DEFAULT|" <<< $OLDFS)
    echo "cloning $OLDFS to $NEWFS"
    zfs clone -o canmount=noauto -o mountpoint=none "$OLDFS@lastboot" "$NEWFS"
  done

  zfs set mountpoint=/ "$BASE/$LASTBOOT-$DEFAULT"

  # backup the current UKI
  echo "copying $UKI_NAME to lastboot.efi"
  cp "$EFI_DIR/EFI/Linux/$UKI_NAME" "$EFI_DIR/EFI/Linux/lastboot.efi"
else
  echo "not booted to $BASE/$DEFAULT, taking no action"
fi