#!/usr/bin/env bash

# omarchy:summary=Create or restore system snapshots with snapper
# omarchy:args=<create|restore>
# omarchy:requires-sudo=true

set -e

COMMAND="$1"

if [[ -z $COMMAND ]]; then
  echo "Usage: omarchy-snapshot <create|restore>" >&2
  exit 1
fi

# Based: snapper and its boot entries are the Arch install's; a Debian
# image and a Mac have nothing here to snapshot or restore.
[[ $(omarchy-os) == arch ]] || { echo "omarchy-snapshot: snapper snapshots are the Arch install's; nothing to snapshot on $(omarchy-os); see /usr/share/doc/omarchy/README.source" >&2; exit 0; }

if omarchy-cmd-missing snapper; then
  exit 127 # omarchy-update can use this to just ignore if snapper is not available
fi

case "$COMMAND" in
create)
  # The description is just a label, so never let it abort the snapshot.
  DESC="$(omarchy-version 2>/dev/null || echo unknown)"

  # Get existing snapper config names from CSV output
  mapfile -t CONFIGS < <(sudo snapper --csvout list-configs | awk -F, 'NR>1 {print $1}')

  # Snapper installed but unconfigured snapshots nothing. Staying quiet here
  # reads as a successful snapshot, so the next update looks recoverable when
  # nothing has ever been captured.
  if (( ${#CONFIGS[@]} == 0 )); then
    echo -e "\e[33mNo Snapper configs found, so no snapshot was created.\e[0m" >&2
    echo "Configure Snapper with: sudo bash -euo pipefail \"$OMARCHY_PATH/install/config/snapper.sh\"" >&2
    exit 1
  fi

  echo -e "\e[32mCreate system snapshot\e[0m"

  for config in "${CONFIGS[@]}"; do
    sudo snapper -c "$config" create -c number -d "$DESC"
    sudo snapper -c "$config" cleanup number
  done

  echo "Snapshots can be selected during boot."
  ;;
restore)
  # Based: limine-snapper-restore is the Arch boot-entry tool; roll back
  # with snapper's own undochange or from the GRUB snapshot menu.
  echo "omarchy-snapshot restore: managed by apt on Based; see /usr/share/doc/omarchy/README.source" >&2
  ;;
esac
