#!/bin/bash
set -e

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
  echo -e "\033[1;33m-->\033[1;34m Creating nix subvolume\033[0m"
  btrfs subvolume create $MNT_DIR/@nix
fi

umount "$MNT_DIR"
rmdir "$MNT_DIR"

echo -e "\033[1;33m-->\033[1;34m Mounting nix subvolume\033[0m"
mkdir -p /nix
echo "UUID=$BTRFS_UUID /nix btrfs subvol=@nix,nodatacow,x-initrd.mount 0 0" >> /etc/fstab
mount -a

if [ ! -e "/nix/var/nix/profiles/default" ]; then
  echo -e "\n\033[1;33m-->\033[1;34m Installing Nix 🍵\033[0m\n"
  sh <(curl -L https://nixos.org/nix/install) < /dev/null --daemon

  echo -e "\n\033[1;33m-->\033[1;34m Configuring Nix\033[0m"
  cat >> /etc/nix/nix.conf << EOF
experimental-features = nix-command flakes
extra-trusted-public-keys = nyx.chaotic.cx-1:HfnXSw4pj95iI/n17rIDy40agHj12WfF+Gqk6SonIT8= chaotic-nyx.cachix.org-1:HfnXSw4pj95iI/n17rIDy40agHj12WfF+Gqk6SonIT8=
extra-substituters = https://nyx.chaotic.cx
EOF
fi

echo -e "\033[1;33m-->\033[1;34m Launching installer 🍵\033[0m"
/nix/var/nix/profiles/default/bin/nix develop --refresh --accept-flake-config gitlab:garuda-linux/garuda-nix-subsystem/v2#gns-install -c "gns-install"