#!/bin/sh
#
# install-hooks.sh
#
# Installs the optional `pre-push` git hook that runs validate-concepts.sh
# before every push. Idempotent: re-running this script does not duplicate
# the hook or break an existing one.
#
# Usage:
#   scripts/install-hooks.sh
#
# The hook is a small wrapper around scripts/validate-concepts.sh; it does
# not block pushes. The validator always exits 0.

set -eu

REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || true)
if [ -z "$REPO_ROOT" ]; then
    printf 'install-hooks: not inside a git repository.\n' >&2
    exit 1
fi

HOOK_DIR=$(git -C "$REPO_ROOT" rev-parse --git-path hooks)
HOOK_PATH="$HOOK_DIR/pre-push"
HOOK_MARKER="# AMPERE_CONCEPT_VALIDATOR_HOOK"

mkdir -p "$HOOK_DIR"

# Body is the snippet we drop into pre-push. It is wrapped in a marker block
# so re-running this script can find and replace prior installations without
# touching unrelated content.
HOOK_SNIPPET="
${HOOK_MARKER}_BEGIN
# Concept staleness validator. Informs only; never blocks pushes.
if [ -x \"\$(git rev-parse --show-toplevel)/scripts/validate-concepts.sh\" ]; then
    \"\$(git rev-parse --show-toplevel)/scripts/validate-concepts.sh\" --base @{push} --head HEAD || true
fi
${HOOK_MARKER}_END
"

if [ -f "$HOOK_PATH" ]; then
    if grep -q "${HOOK_MARKER}_BEGIN" "$HOOK_PATH" 2>/dev/null; then
        # Replace the existing block in-place. Use awk to drop everything
        # between the markers (inclusive), then append the new snippet.
        TMP=$(mktemp)
        awk -v marker="$HOOK_MARKER" '
            $0 ~ marker"_BEGIN" { skipping = 1; next }
            $0 ~ marker"_END"   { skipping = 0; next }
            skipping != 1       { print }
        ' "$HOOK_PATH" > "$TMP"
        printf '%s\n' "$HOOK_SNIPPET" >> "$TMP"
        mv "$TMP" "$HOOK_PATH"
    else
        # Append to an existing hook we did not write.
        printf '%s\n' "$HOOK_SNIPPET" >> "$HOOK_PATH"
    fi
else
    {
        printf '#!/bin/sh\n'
        printf '# Generated by scripts/install-hooks.sh.\n'
        printf '%s\n' "$HOOK_SNIPPET"
    } > "$HOOK_PATH"
fi

chmod +x "$HOOK_PATH"

printf 'install-hooks: pre-push hook installed at %s\n' "$HOOK_PATH"
printf 'install-hooks: re-running this script is safe (idempotent).\n'
