#!/bin/bash
set -eou pipefail

# Full uninstall of Nix and direnv — use only when you need a clean slate.
# If you just want to stop direnv from auto-activating, use dev/direnv-down instead.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
ENVRC_PATH="$REPO_ROOT/.envrc"

echo "=============================================="
echo "WARNING: This fully uninstalls Nix and direnv."
echo "=============================================="
echo ""
echo "Re-installing with dev/nix-up will require re-downloading"
echo "all dependencies, which can take 5+ minutes depending on"
echo "your connection speed."
echo ""
echo "If you just want to temporarily disable direnv (the shell"
echo "hook that auto-activates the Nix environment), run instead:"
echo ""
echo "  dev/direnv-down"
echo ""
read -p "Continue with full Nix uninstall? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
  echo "Aborted. Consider using dev/direnv-down to disable direnv without uninstalling."
  exit 0
fi

# Deactivate direnv environment before uninstalling
if which direnv &> /dev/null; then
  echo "Deactivating direnv environment..."
  direnv deny "$REPO_ROOT" 2>/dev/null || true
fi

# Remove .envrc file created by nix-up
if [[ -f "$ENVRC_PATH" ]]; then
  echo "Removing .envrc file..."
  rm "$ENVRC_PATH"
fi

if which nix &>/dev/null; then
  read -p "Are you sure you want to uninstall nix? (y/n) " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    /nix/nix-installer uninstall
  else
    echo "Nix uninstall cancelled."
    exit 1
  fi
else
  echo "No nix installation detected"
fi

if which direnv &> /dev/null; then
  if [[ "$OSTYPE" == "darwin"* ]]; then
    brew remove direnv
  elif [[ -f /etc/arch-release ]]; then
    sudo pacman -Rns direnv
  elif grep -q "ubuntu" /etc/os-release 2>/dev/null; then
    sudo apt remove direnv
  fi
fi

# Remove direnv shell hooks from rc files
for shell_rc in ~/.bashrc ~/.zshrc; do
  if [[ -f "$shell_rc" ]] && grep -q "direnv hook" "$shell_rc"; then
    sed '/direnv hook/d' "$shell_rc" > "$shell_rc.tmp" && mv "$shell_rc.tmp" "$shell_rc"
    echo "Removed direnv hook from $shell_rc"
  fi
done
# Handle fish shell config
FISH_CONFIG=~/.config/fish/config.fish
if [[ -f "$FISH_CONFIG" ]] && grep -q "direnv hook" "$FISH_CONFIG"; then
  sed '/direnv hook/d' "$FISH_CONFIG" > "$FISH_CONFIG.tmp" && mv "$FISH_CONFIG.tmp" "$FISH_CONFIG"
  echo "Removed direnv hook from $FISH_CONFIG"
fi

echo ""
echo "=============================================="
echo "IMPORTANT: Start a new terminal session!"
echo "=============================================="
echo ""
echo "Environment variables from the Nix shell (like DEVELOPER_DIR,"
echo "SDKROOT) persist in your current session. To clear them, either:"
echo ""
echo "  1. Open a new terminal window (recommended), or"
echo ""
echo "  2. Run this in your current shell:"
echo "     unset DEVELOPER_DIR SDKROOT NIX_LDFLAGS NIX_CFLAGS_COMPILE"
echo ""
