#!/bin/bash
set -eou pipefail

# Local script install & configure nix
if ! which nix &>/dev/null; then
  echo "Please review the installation script at:"
  echo "https://install.determinate.systems/nix"
  read -p "Do you want to proceed with the installation? (y/n) " -n 1 -r
  echo
  if [[ $REPLY =~ ^[Yy]$ ]]; then
    curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | sh -s -- install --determinate
  else
    echo "Nix installation aborted."
  fi
else
  echo "detected existing nix installation"
fi

./dev/nix-cache-up
echo "direnv will automatically enter the default nix environment upon entering a configured directory"
read -p "install direnv? (y/n) " -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
  [[ "$OSTYPE" == "darwin"* ]] && brew install direnv
  [[ -f /etc/arch-release ]] && sudo pacman -S direnv
  grep -q "ubuntu" /etc/os-release 2>/dev/null && sudo apt install direnv
  echo ""
  echo "installing shell hooks for bash/zsh/fish"
  # Check if hook already exists before appending
  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
    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
else
  echo "direnv not installed"
fi

# Create .envrc file for omnix integration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
ENVRC_PATH="$REPO_ROOT/.envrc"

if [[ -f "$ENVRC_PATH" ]]; then
  echo ".envrc already exists at $ENVRC_PATH"
else
  echo "Creating .envrc file..."
  cat > "$ENVRC_PATH" << 'EOF'
source_url \
  https://omnix.page/om/develop/omnixrc/v1 \
  'sha256-FBAVRYkaexKeFKQGUxaPHqhBnqA7km7++O77dKiyD0I='
watch_file om.yaml
use omnix
EOF
  echo ".envrc created at $ENVRC_PATH"
fi

# Allow direnv (needed after nix-down which runs direnv deny)
if which direnv &>/dev/null; then
  echo "Allowing direnv environment..."
  direnv allow "$REPO_ROOT"
fi

echo ""
echo "=============================================="
echo "Setup complete! Reload your shell to activate:"
echo "=============================================="
echo ""
echo "  exec \$SHELL"
echo ""
