#!/usr/bin/env bash

# Toggle dedicated vs integrated GPU mode via supergfxd (for hybrid gpu laptops, like Asus G14).
# Declarative enablement + Runtime mode switching for Nomarchy NixOS.

FEATURE_FILE="/etc/nixos/nomarchy-features/supergfxd.nix"

if ! command -v supergfxctl &> /dev/null; then
    sudo mkdir -p "/etc/nixos/nomarchy-features"
    cat <<EOF | sudo tee "$FEATURE_FILE" > /dev/null
{ config, pkgs, ... }:
{
  services.supergfxd.enable = true;
}
EOF
    echo "Created $FEATURE_FILE to enable supergfxd."
    echo "IMPORTANT: To finish enabling hybrid GPU support, add './nomarchy-features/supergfxd.nix' to your imports list in /etc/nixos/system.nix or /etc/nixos/flake.nix,"
    echo "then run 'sys-update'."
    exit 0
fi

gpu_mode=$(supergfxctl -g)
echo "Current GPU mode: $gpu_mode"

case "$gpu_mode" in
"Integrated")
  if gum confirm "Switch to Hybrid mode (enables dGPU) and reboot?"; then
    supergfxctl -m Hybrid
    echo "Switching to Hybrid mode..."
    nomarchy-system-reboot
  fi
  ;;
"Hybrid")
  if gum confirm "Switch to Integrated mode (disables dGPU) and reboot?"; then
    supergfxctl -m Integrated
    echo "Switching to Integrated mode..."
    nomarchy-system-reboot
  fi
  ;;
*)
  echo "Hybrid GPU in unknown mode: $gpu_mode. Try 'supergfxctl -m Hybrid' manually."
  exit 1
  ;;
esac
