#!/usr/bin/env bash
set -euo pipefail

repo_root="$(git rev-parse --show-toplevel)"
hook_path="$(git rev-parse --path-format=absolute --git-path hooks/pre-commit)"
expected="$(printf '#!/usr/bin/env bash\nexec %q \"$@\"' "$repo_root/scripts/pre-commit")"

if [ "${1:-}" = "--check" ]; then
  if [ -x "$hook_path" ] && [ "$(cat "$hook_path")" = "$expected" ]; then
    printf 'BioMCP pre-commit hook is current at %s\n' "$hook_path"
    exit 0
  fi
  if [ -e "$hook_path" ]; then
    printf 'BioMCP pre-commit hook is stale at %s. Run: scripts/install-pre-commit-hook\n' "$hook_path" >&2
  else
    printf 'BioMCP pre-commit hook is missing at %s. Run: scripts/install-pre-commit-hook\n' "$hook_path" >&2
  fi
  exit 1
fi

if [ "$#" -ne 0 ]; then
  printf 'Usage: scripts/install-pre-commit-hook [--check]\n' >&2
  exit 2
fi

mkdir -p "$(dirname "$hook_path")"
printf '#!/usr/bin/env bash\nexec %q "$@"\n' "$repo_root/scripts/pre-commit" >"$hook_path"
chmod +x "$hook_path"
printf 'Installed BioMCP pre-commit hook at %s\n' "$hook_path"
