#!/usr/bin/env bash
# post-checkout — auto-install hooks into every worktree after a worktree add.
#
# git fires post-checkout after both `git checkout` and `git worktree add`.
# We distinguish a new-worktree creation from a regular branch switch using
# the third argument: flag=1 means branch checkout, flag=0 means file checkout.
# For worktree add the flag is always 1 (branch), but this hook runs in the
# *newly created* worktree, not the original — so its hooks dir starts empty.
# Installing here means any `git worktree add` automatically wires up hooks
# without a manual `scripts/install-hooks.sh` step.
#
# Arguments (passed by git):
#   $1  previous HEAD
#   $2  new HEAD
#   $3  flag: 1 = branch/worktree checkout, 0 = file checkout

set -euo pipefail

FLAG="${3:-1}"
# Only run for branch checkouts (including new worktrees), not file checkouts.
[[ "$FLAG" == "0" ]] && exit 0

REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null)" || exit 0
INSTALL_SCRIPT="$REPO_ROOT/scripts/install-hooks.sh"

if [[ -x "$INSTALL_SCRIPT" ]]; then
    # Run quietly so the user doesn't see noise on every checkout.
    "$INSTALL_SCRIPT" --quiet 2>/dev/null || true
fi
