#!/bin/bash
set -e

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

BTRFS_UUID="$(findmnt -n -o UUID /)"
MNT_DIR="$(mktemp -d)"

# Check if the root is of type BTRFS
if [ "$(stat -f -c %T /)" != "btrfs" ]; then
  echo -e "\033[1;31mError: Root partition is not of type BTRFS. Garuda Nix Subsystem only supports BTRFS. ❌\033[0m";
  exit 1
fi

mount "UUID=$BTRFS_UUID" "$MNT_DIR"

if ! [ -d "$MNT_DIR/@nix" ]; then
  if [ -d "/nix" ]; then
    echo -e "\033[1;31mError: /nix already exists. Please uninstall and fully remove any nix installations before you continue. ❌\033[0m";
    exit 1
  fi
  step "Creating nix subvolume"
  btrfs subvolume create $MNT_DIR/@nix
fi

umount "$MNT_DIR"
rmdir "$MNT_DIR"

step "Mounting nix subvolume"
mkdir -p /nix
if ! grep -q "[[:space:]]/nix[[:space:]].*subvol=@nix" /etc/fstab 2>/dev/null; then
  echo "UUID=$BTRFS_UUID /nix btrfs subvol=@nix,nodatacow,x-initrd.mount 0 0" >> /etc/fstab
  systemctl daemon-reload 2>/dev/null || true
fi
if ! mountpoint -q /nix 2>/dev/null; then
  mount /nix || mount -a
fi

if [ ! -e "/nix/var/nix/profiles/default" ]; then
  step "Installing Nix 🍵"
  echo
  curl -sSf -L https://install.lix.systems/lix | sh -s -- install --no-confirm

  step "Configuring Nix"
  cat >> /etc/nix/nix.conf << EOF
experimental-features = nix-command flakes
extra-trusted-public-keys = nyx-cache.chaotic.cx:dJxTrgMC3V3cFfyIiBQDQorG6k1LsqurH/srpMSq7qk=
extra-substituters = https://nyx-cache.chaotic.cx
EOF
fi

step "Launching installer 🍵"
/nix/var/nix/profiles/default/bin/nix develop --quiet --refresh --accept-flake-config gitlab:garuda-linux/garuda-nix-subsystem/stable#gns-install -c gns-install "$@"