#!/bin/bash
set -eou pipefail

# Re-enable direnv for this repo
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"

if ! which direnv &>/dev/null; then
  echo "direnv is not installed. Run dev/nix-up to set up the full environment."
  exit 1
fi

if [[ ! -f "$REPO_ROOT/.envrc" ]]; then
  echo "No .envrc found. Run dev/nix-up to set up the full environment."
  exit 1
fi

echo "Allowing direnv environment for this repo..."
direnv allow "$REPO_ROOT"

# Re-add direnv shell hook if missing (e.g. after direnv-down)
for shell_rc in ~/.bashrc ~/.zshrc; do
  if [[ -f "$shell_rc" ]] && ! grep -q "direnv hook" "$shell_rc"; then
    case "$shell_rc" in
      *bashrc) echo 'eval "$(direnv hook bash)"' >> "$shell_rc" ;;
      *zshrc) echo 'eval "$(direnv hook zsh)"' >> "$shell_rc" ;;
    esac
    echo "Added direnv hook to $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
  echo 'direnv hook fish | source' >> "$FISH_CONFIG"
  echo "Added direnv hook to $FISH_CONFIG"
fi

echo ""
echo "direnv re-enabled. Your shell will auto-activate the Nix environment."
echo "To disable: dev/direnv-down"
