#!/bin/bash
set -e

step() {
  if [ -t 1 ]; then
    echo -e "\033[1;32m»\033[0m $*"
  else
    echo "» $*"
  fi
}

if [[ $EUID -ne 0 ]]; then
  echo -e "\033[1;31mError: Uninstaller must run as root. Use garuda-nix-subsystem uninstall. ❌\033[0m"
  exit 1
fi

YES=false
DRY=false
for arg in "$@"; do
  case "$arg" in
    --yes|-y) YES=true ;;
    --dry-run|-n) DRY=true ;;
    *) echo "Unknown option: $arg (use --dry-run/-n or --yes/-y)" >&2; exit 1 ;;
  esac
done

BTRFS_UUID="$(findmnt -n -o UUID /)"
MNT_DIR="$(mktemp -d)"
mount "UUID=$BTRFS_UUID" "$MNT_DIR"
trap 'umount "$MNT_DIR" 2>/dev/null || true; rmdir "$MNT_DIR" 2>/dev/null || true' EXIT

HAS_SUBSYSTEM=false
[ -d "$MNT_DIR/@nix-subsystem" ] && HAS_SUBSYSTEM=true
HAS_NIX=false
[ -d "$MNT_DIR/@nix" ] && HAS_NIX=true

if ! $HAS_SUBSYSTEM && ! $HAS_NIX; then
  echo "Garuda Nix Subsystem is not installed. Nothing to do."
  exit 0
fi

step "This will delete:"
if $HAS_SUBSYSTEM; then echo "  - subvolume @nix-subsystem"; fi
if $HAS_NIX; then echo "  - subvolume @nix"; fi

if $DRY; then
  echo "Dry run - nothing was changed."
  exit 0
fi

if ! $YES; then
  read -rp "? Continue? [y/N] " answer
  if [[ "$answer" != "y" && "$answer" != "Y" ]]; then
    echo "Aborted."
    exit 1
  fi
fi

echo
step "Uninstalling Nix"
if [ -x /nix/nix-installer ]; then
  /nix/nix-installer uninstall --no-confirm || true
else
  curl -sSf -L https://install.lix.systems/lix | sh -s -- uninstall --no-confirm || true
fi

step "Unmounting subsystem subvolumes"
while IFS= read -r mnt; do
  umount "$mnt" 2>/dev/null || umount -l "$mnt" 2>/dev/null \
    || echo "warning: could not unmount $mnt" >&2
done < <(tac /proc/mounts | awk '$3 == "btrfs" && match($4, /subvol=\/@nix(-subsystem)?(,|$)/) {print $2}')

umount /nix 2>/dev/null || umount -l /nix 2>/dev/null || true

# Delete nested subvolumes/snapshots deepest-first ($1 relative to fs root)
delete_nested() {
  btrfs subvolume list -o "$MNT_DIR/$1" 2>/dev/null | awk '{print $NF}' \
    | awk -F/ '{print (NF-1) " " $0}' | sort -rn | cut -d' ' -f2- \
    | while IFS= read -r sub; do
        btrfs property set -ts "$MNT_DIR/$sub" ro false 2>/dev/null || true
        btrfs subvolume delete "$MNT_DIR/$sub"
      done
}

if $HAS_SUBSYSTEM; then
  step "Deleting @nix-subsystem subvolume"
  delete_nested @nix-subsystem
  btrfs subvolume delete "$MNT_DIR/@nix-subsystem"
fi
if $HAS_NIX; then
  step "Deleting @nix subvolume"
  umount /nix 2>/dev/null || true
  btrfs subvolume delete "$MNT_DIR/@nix"
  rm -rf /nix 2>/dev/null || true
fi

step "Removing /nix from /etc/fstab"
cp -a /etc/fstab /etc/fstab.gns-bak
sed -i '/[[:space:]]\/nix[[:space:]].*subvol=@nix\([,[:space:]]\)/d' /etc/fstab

step "Removing Garuda Nix Subsystem grub entry"
rm -f /etc/grub.d/25-garudanix

step "Garuda Nix Subsystem uninstalled. 🍵"
echo "If your host bootloader picked up the subsystem (os-prober), re-run grub-mkconfig."
