#!/usr/bin/env bash
# Install Mugi git hooks into .git/hooks/.
#
# Usage:
#   bash scripts/install_git_hooks.sh             # pre-commit + post-commit (always-on)
#   bash scripts/install_git_hooks.sh --with-swift  # also installs slow Swift pre-push
#
# Existing non-Mugi hooks are preserved as <hook>.local and chained from the new
# hook so we coexist with pre-commit framework, husky, etc.
#
# Reverse with scripts/uninstall_git_hooks.sh.
set -euo pipefail

cd "$(dirname "$0")/.."
hooks_src="scripts/git-hooks"
hooks_dst=".git/hooks"

WITH_SWIFT=0
for arg in "$@"; do
  case "$arg" in
    --with-swift) WITH_SWIFT=1 ;;
    *) echo "[install] unknown arg: $arg"; exit 2 ;;
  esac
done

if [ ! -d "$hooks_src" ]; then
  echo "[install] expected $hooks_src to exist; aborting."
  exit 1
fi
if [ ! -d ".git" ]; then
  echo "[install] not in a git working tree; aborting."
  exit 1
fi
mkdir -p "$hooks_dst"

install_one() {
  local hook="$1"
  local src="$hooks_src/$hook"
  local dst="$hooks_dst/$hook"
  if [ ! -f "$src" ]; then
    echo "[install] missing source $src; skipping."
    return
  fi
  chmod +x "$src"
  if [ -f "$dst" ] && [ ! -L "$dst" ]; then
    if grep -q "Mugi" "$dst" 2>/dev/null; then
      # Already a Mugi hook; just refresh.
      :
    else
      mv "$dst" "$dst.local"
      chmod +x "$dst.local" 2>/dev/null || true
      echo "[install] preserved existing $hook -> $hook.local (chained)"
    fi
  fi
  ln -sf "../../$src" "$dst"
  echo "[install] $hook -> $src"
}

install_one pre-commit
install_one post-commit
if [ "$WITH_SWIFT" = "1" ]; then
  install_one pre-push
  echo "[install] Swift pre-push hook ENABLED (slow ~30-60s on Swift changes)."
fi

echo ""
echo "[install] Done. Verify with: git config core.hooksPath || ls -l .git/hooks/"
echo "[install] Smoke gate: 'make smoke'  Plan-scope check: 'make plan-scope'"
echo "[install] Reverse:    'bash scripts/uninstall_git_hooks.sh'"
