#!/usr/bin/env bash
# snapper-sdboot: systemd-boot entries for the snapper snapshots of /.
#   snapper-sdboot sync   add entries for new snapshots, drop those of deleted ones
#   snapper-sdboot list   print the snapshot entries on the ESP
#   snapper-sdboot clean  remove all snapshot entries and UKIs from the ESP
#   snapper-sdboot pin <number>...    give the snapshots their entry first
#   snapper-sdboot unpin <number>...  remove the pin
#   snapper-sdboot pins   print the pinned snapshots
#
# Snapshots with the same kernel version and the same initramfs share one
# multi-profile UKI, built from the kernel and initramfs in their /boot. Each
# snapshot is one profile of it, with the snapshot's own /etc/kernel/cmdline
# plus rootflags=subvol=<snapshot>. btrfs takes the last subvol=, so the
# snapshot is mounted. A Type #1 entry per snapshot selects its profile.
# Read-only snapshots get their writable overlay from the dracut module
# 50btrfs-snapshot-overlay (garuda-dracut-support).
#
# The UKIs live in EFI/snapper-sdboot/<pkgbase>-<version>-<initramfs hash>/
# and not in EFI/Linux, so systemd-boot does not list them on its own and
# kernel-install never removes them. Settings: /etc/snapper-sdboot.conf.
# Snapshots with the snapper userdata sdboot=pin get their entry first.

set -euo pipefail

FREE_SPACE_FLOOR_MIB=512
MAX_GROUPS=10
SKIP_TYPES="post"

# shellcheck source=/dev/null
[[ -f /etc/snapper-sdboot.conf ]] && . /etc/snapper-sdboot.conf

readonly SNAPSHOTS=/.snapshots
readonly NAME=snapper-sdboot

# The PE header of the systemd-stub UKI holds 60 joined profiles (systemd 262)
readonly MAX_PER_KERNEL=60

# the snapshot list of the last sync_once round
SYNCED=""

log() { echo "$NAME: $*"; }
warn() { echo "$NAME: $*" >&2; }

lock() {
  mkdir -p /run/lock
  exec 9>"/run/lock/$NAME.lock"
  flock 9
}

# field <info.xml> <tag>: the text of a top-level tag of a snapper info.xml
field() {
  sed -n "s|.*<$2>\(.*\)</$2>.*|\1|p" "$1" | head -n1 |
    sed -e 's/&lt;/</g' -e 's/&gt;/>/g' -e 's/&quot;/"/g' -e "s/&apos;/'/g" -e 's/&amp;/\&/g'
}

# The snapshot numbers that get an entry, newest first
wanted_snapshots() {
  local dir n type
  for dir in "$SNAPSHOTS"/[0-9]*/; do
    n="${dir%/}"
    n="${n##*/}"
    [[ "$n" =~ ^[0-9]+$ ]] || continue
    [[ -f "$dir/info.xml" && -d "$dir/snapshot" ]] || continue
    type="$(field "$dir/info.xml" type)"
    [[ " $SKIP_TYPES " == *" $type "* ]] && continue
    echo "$n"
  done | sort -rn
}

is_pinned() {
  tr -d ' \t\n' <"$SNAPSHOTS/$1/info.xml" | grep -q '<userdata><key>sdboot</key><value>pin</value></userdata>'
}

# budget_order <snapshot>...: the pinned snapshots, then the others, each in the given order
budget_order() {
  local n pinned=() others=()
  for n in "$@"; do
    if is_pinned "$n"; then
      pinned+=("$n")
    else
      others+=("$n")
    fi
  done
  printf '%s\n' "${pinned[@]}" "${others[@]}" | sed '/^$/d'
}

size_k() {
  du -sk "$1" 2>/dev/null | cut -f1
}

# kernel_of <snapshot root>: prints "<pkgbase> <kernel version>". The booted
# kernel package if the snapshot has it, otherwise its first kernel.
kernel_of() {
  local snap="$1" booted="" pkgbase="" file
  booted="$(cat "/usr/lib/modules/$(uname -r)/pkgbase" 2>/dev/null || true)"

  if [[ -n "$booted" && -f "$snap/boot/vmlinuz-$booted" ]]; then
    pkgbase="$booted"
  else
    for file in "$snap"/boot/vmlinuz-*; do
      [[ -f "$file" ]] || continue
      pkgbase="${file##*/vmlinuz-}"
      break
    done
  fi

  [[ -n "$pkgbase" ]] || return 1

  for file in "$snap"/usr/lib/modules/*/pkgbase; do
    [[ -f "$file" && "$(<"$file")" == "$pkgbase" ]] || continue
    file="${file%/pkgbase}"
    echo "$pkgbase ${file##*/}"
    return 0
  done

  return 1
}

# group_of <snapshot number>: prints "<group> <pkgbase> <kernel version>", the
# group being the UKI directory the snapshot belongs to
group_of() {
  local n="$1" snap="$SNAPSHOTS/$1/snapshot" kernel pkgbase kver hash

  if ! kernel="$(kernel_of "$snap")"; then
    warn "snapshot $n has no kernel in /boot, no entry"
    return 1
  fi
  pkgbase="${kernel%% *}"
  kver="${kernel#* }"

  if [[ ! -f "$snap/boot/initramfs-$pkgbase.img" ]]; then
    warn "snapshot $n has no /boot/initramfs-$pkgbase.img, no entry"
    return 1
  fi

  hash="$(sha256sum "$snap/boot/initramfs-$pkgbase.img" | cut -c1-12)"
  echo "$pkgbase-$kver-$hash $pkgbase $kver"
}

# cmdline_of <snapshot number> <subvolume>: the kernel command line of the
# snapshot's profile
cmdline_of() {
  local cmdline="$SNAPSHOTS/$1/snapshot/etc/kernel/cmdline"
  [[ -s "$cmdline" ]] || cmdline=/etc/kernel/cmdline

  if [[ ! -s "$cmdline" ]]; then
    warn "no /etc/kernel/cmdline in snapshot $1 or on the system"
    return 1
  fi

  echo "$(tr '\n' ' ' <"$cmdline") rootflags=subvol=$2"
}

write_entry() {
  local esp="$1" n="$2" group="$3" profile="$4" info="$SNAPSHOTS/$2/info.xml" title date description
  date="$(field "$info" date)"
  description="$(field "$info" description)"
  title="Garuda Linux snapshot $n${date:+, ${date% *}}${description:+: $description}"
  title="${title//$'\n'/ }"

  mkdir -p "$esp/loader/entries"
  {
    echo "title    $title"
    echo "version  $n"
    echo "sort-key $NAME"
    echo "uki      /EFI/$NAME/$group/snapshots.efi"
    echo "profile  $profile"
  } >"$esp/loader/entries/$NAME-$n.conf.tmp"
  mv "$esp/loader/entries/$NAME-$n.conf.tmp" "$esp/loader/entries/$NAME-$n.conf"
}

# build <esp> <group> <pkgbase> <kernel version> <subvolume prefix> <snapshot>...:
# the UKI of a group, one profile per snapshot in the given order. Profile 0 is
# the base of the UKI, the snapshots start at profile 1.
build() {
  local esp="$1" group="$2" pkgbase="$3" kver="$4" subvol_prefix="$5"
  shift 5
  local dir="$esp/EFI/$NAME/$group" snap="$SNAPSHOTS/$1/snapshot" joins=() n cmdline base_cmdline=""

  rm -rf -- "$dir.tmp"
  mkdir -p "$dir.tmp/profiles"

  for n in "$@"; do
    cmdline="$(cmdline_of "$n" "$subvol_prefix/$n/snapshot")" || {
      rm -rf -- "$dir.tmp"
      return 1
    }
    [[ -n "$base_cmdline" ]] || base_cmdline="$cmdline"

    if ! ukify build --profile="ID=snapshot-$n
TITLE=Snapshot $n" --cmdline="$cmdline" --output="$dir.tmp/profiles/$n.efi" >/dev/null; then
      rm -rf -- "$dir.tmp"
      return 1
    fi

    joins+=("--join-profile=$dir.tmp/profiles/$n.efi")
  done

  sed 's/^PRETTY_NAME="\(.*\)"$/PRETTY_NAME="\1 (snapshot)"/' \
    "$snap/usr/lib/os-release" >"$dir.tmp/os-release"

  local config=()
  [[ -f /etc/kernel/uki.conf ]] && config=(--config=/etc/kernel/uki.conf)

  if ! ukify build "${config[@]}" --linux="$snap/boot/vmlinuz-$pkgbase" \
    --initrd="$snap/boot/initramfs-$pkgbase.img" --cmdline="$base_cmdline" \
    --uname="$kver" --os-release="@$dir.tmp/os-release" "${joins[@]}" \
    --output="$dir.tmp/snapshots.efi" >/dev/null; then
    rm -rf -- "$dir.tmp"
    return 1
  fi

  rm -rf -- "$dir.tmp/profiles" "$dir.tmp/os-release"
  echo "$*" >"$dir.tmp/members"
  rm -rf -- "$dir"
  mv "$dir.tmp" "$dir"
  log "built $group for snapshots $*"
}

present_entries() {
  local path n
  for path in "$1/loader/entries/$NAME"-*.conf; do
    [[ -e "$path" ]] || continue
    n="${path##*/"$NAME"-}"
    n="${n%.conf}"
    [[ "$n" =~ ^[0-9]+$ ]] && echo "$n"
  done
}

present_groups() {
  local path
  for path in "$1/EFI/$NAME"/*/; do
    [[ -d "$path" ]] || continue
    path="${path%/}"
    echo "${path##*/}"
  done
}

sync_once() {
  local esp="$1" subvol_prefix="$2"
  local wanted=() keep=() n info group version size budget existing_k=0 avail_k groups=0
  local -A group_of_n=() kernel_of_group=() members=() per_version=() counted=() skipped=()

  mapfile -t wanted < <(wanted_snapshots)

  [[ -d "$esp/EFI/$NAME" ]] && existing_k="$(size_k "$esp/EFI/$NAME")"
  avail_k="$(df --output=avail -k "$esp" | tail -n1 | tr -d ' ')"

  # Pinned first, then newest first, within the free-space floor and
  # MAX_GROUPS. A snapshot only costs space when it starts a new UKI.
  budget=$((avail_k + existing_k - FREE_SPACE_FLOOR_MIB * 1024))
  for n in $(budget_order "${wanted[@]}"); do
    info="$(group_of "$n")" || continue
    group="${info%% *}"
    version="${info#* }"

    if ((${per_version[$version]:-0} >= MAX_PER_KERNEL)) || [[ -n "${skipped[$group]:-}" ]]; then
      continue
    fi

    if [[ -z "${counted[$group]:-}" ]]; then
      if ((groups >= MAX_GROUPS)); then
        warn "no entry for snapshot $n and others of $group, MAX_GROUPS=$MAX_GROUPS reached"
        skipped[$group]=1
        continue
      fi

      if [[ -f "$esp/EFI/$NAME/$group/snapshots.efi" ]]; then
        size="$(size_k "$esp/EFI/$NAME/$group")"
      else
        size=$(($(size_k "$SNAPSHOTS/$n/snapshot/boot/vmlinuz-${version%% *}") + $(size_k "$SNAPSHOTS/$n/snapshot/boot/initramfs-${version%% *}.img") + 256))
      fi

      if ((size > budget)); then
        warn "the ESP has no room for snapshot $n and others of $group (floor ${FREE_SPACE_FLOOR_MIB} MiB)"
        skipped[$group]=1
        continue
      fi

      budget=$((budget - size))
      groups=$((groups + 1))
      counted[$group]=1
      kernel_of_group[$group]="$version"
    fi

    per_version[$version]=$((${per_version[$version]:-0} + 1))
    group_of_n[$n]="$group"
    keep+=("$n")
  done

  # Oldest first, so a new snapshot keeps the profile numbers of the others
  for n in $(printf '%s\n' "${keep[@]}" | sort -n); do
    members[${group_of_n[$n]}]+="${members[${group_of_n[$n]}]:+ }$n"
  done

  for n in $(present_entries "$esp"); do
    if [[ -z "${group_of_n[$n]:-}" ]]; then
      rm -f "$esp/loader/entries/$NAME-$n.conf"
      log "removed snapshot $n"
    fi
  done

  for group in $(present_groups "$esp"); do
    [[ -n "${members[$group]:-}" ]] || rm -rf -- "${esp:?}/EFI/$NAME/$group"
  done

  local built=() profile
  for group in "${!members[@]}"; do
    if [[ -f "$esp/EFI/$NAME/$group/snapshots.efi" &&
      "$(cat "$esp/EFI/$NAME/$group/members" 2>/dev/null)" == "${members[$group]}" ]]; then
      built+=("$group")
      continue
    fi

    # shellcheck disable=SC2086 # members is a list of snapshot numbers
    if build "$esp" "$group" ${kernel_of_group[$group]} "$subvol_prefix" ${members[$group]}; then
      built+=("$group")
    else
      warn "building the UKI of $group failed, its snapshots get no entry"
      for n in ${members[$group]}; do
        rm -f "$esp/loader/entries/$NAME-$n.conf"
      done
    fi
  done

  # Also refreshes the titles after snapper modify
  for group in "${built[@]}"; do
    profile=1
    for n in ${members[$group]}; do
      write_entry "$esp" "$n" "$group" "$profile"
      profile=$((profile + 1))
    done
  done

  SYNCED="$(printf '%s\n' "${wanted[@]}")"
}

cmd_sync() {
  if ! bootctl is-installed --graceful >/dev/null 2>&1; then
    log "systemd-boot is not installed, nothing to do"
    return 0
  fi

  # A snapshot boot runs a read-only copy of the system, its entries stay as they are
  if grep -qE 'subvol=[^ ,]*\.snapshots/[0-9]+/snapshot' /proc/cmdline; then
    log "booted from a snapshot, not changing the entries"
    return 0
  fi
  [[ -d "$SNAPSHOTS" ]] || return 0

  local esp root subvol_prefix
  esp="$(bootctl --print-esp-path)"

  # The subvolume of /, for example /@. The snapshots are below it.
  root="$(findmnt -n -o FSROOT /)"
  root="${root#/}"
  subvol_prefix="${root:+$root/}.snapshots"

  lock

  # Snapshots made while the sync runs are picked up by another round
  for _ in 1 2 3; do
    sync_once "$esp" "$subvol_prefix"
    [[ "$SYNCED" == "$(wanted_snapshots)" ]] && return 0
  done
}

cmd_list() {
  local esp n title
  esp="$(bootctl --print-esp-path)"
  for n in $(present_entries "$esp" | sort -rn); do
    title="$(sed -n 's/^title *//p' "$esp/loader/entries/$NAME-$n.conf")"
    if [[ -f "$SNAPSHOTS/$n/info.xml" ]] && is_pinned "$n"; then
      echo "$title (pinned)"
    else
      echo "$title"
    fi
  done
}

# set_pin <userdata value> <number>...: the snapper plugin then syncs the entries
set_pin() {
  local value="$1" n type
  shift
  (($# > 0)) || {
    warn "no snapshot number given"
    exit 2
  }

  for n in "$@"; do
    if [[ ! "$n" =~ ^[0-9]+$ || ! -f "$SNAPSHOTS/$n/info.xml" ]]; then
      warn "there is no snapshot $n"
      exit 1
    fi
    type="$(field "$SNAPSHOTS/$n/info.xml" type)"
    if [[ -n "$value" && " $SKIP_TYPES " == *" $type "* ]]; then
      warn "snapshot $n is a $type snapshot, which gets no entry (SKIP_TYPES)"
      exit 1
    fi
  done

  local done=unpinned
  [[ -n "$value" ]] && done=pinned
  for n in "$@"; do
    snapper -c root modify --userdata "sdboot=$value" "$n"
    log "$done snapshot $n"
  done
}

cmd_pins() {
  local esp="" n info entry
  bootctl is-installed --graceful >/dev/null 2>&1 && esp="$(bootctl --print-esp-path)"

  for info in "$SNAPSHOTS"/[0-9]*/info.xml; do
    [[ -f "$info" ]] || continue
    n="${info%/info.xml}"
    n="${n##*/}"
    is_pinned "$n" || continue
    entry=""
    [[ -n "$esp" && ! -f "$esp/loader/entries/$NAME-$n.conf" ]] && entry=" (no entry)"
    echo "$n $(field "$info" date) $(field "$info" description)$entry"
  done | sort -rn
}

cmd_clean() {
  bootctl is-installed --graceful >/dev/null 2>&1 || return 0
  local esp n
  esp="$(bootctl --print-esp-path)"

  lock

  for n in $(present_entries "$esp"); do
    rm -f "$esp/loader/entries/$NAME-$n.conf"
    log "removed snapshot $n"
  done

  rm -rf -- "${esp:?}/EFI/$NAME"
}

# The ESP is mounted for root only (umask=0077), so even list needs root
if [[ "${1:-}" =~ ^(sync|list|clean|pin|unpin|pins)$ && $EUID -ne 0 ]]; then
  exec sudo "$0" "$@"
fi

case "${1:-}" in
sync) cmd_sync ;;
list) cmd_list ;;
clean) cmd_clean ;;
pin) set_pin pin "${@:2}" ;;
unpin) set_pin "" "${@:2}" ;;
pins) cmd_pins ;;
*)
  echo "usage: $NAME sync|list|clean|pins|pin <number>...|unpin <number>..." >&2
  exit 2
  ;;
esac
