#!/bin/bash
#
# Contextual post-rewrite hook
# Triggers full re-indexing after amend or rebase operations
#
# Git passes the rewrite type as $1 (either "amend" or "rebase").
# This hook runs as a fully detached background process to never block git.
# It acquires a lock file to prevent concurrent indexing operations.

# Close all file descriptors to fully detach from git
exec 0<&-         # Close stdin
exec 1>/dev/null  # Close stdout
exec 2>/dev/null  # Close stderr

# Get rewrite type from git (either "amend" or "rebase")
REWRITE_TYPE="${1:-unknown}"

# Only process amend and rebase operations
case "$REWRITE_TYPE" in
    amend|rebase)
        ;;
    *)
        # Unknown rewrite type, skip indexing
        exit 0
        ;;
esac

# Check if contextual is available
if ! command -v contextual &> /dev/null; then
    exit 0
fi

# Lock file to prevent concurrent indexing
LOCK_FILE=".git/contextual-index.lock"

# Try to acquire lock (non-blocking)
if ! mkdir "$LOCK_FILE" 2>/dev/null; then
    # Another indexing process is running, skip
    exit 0
fi

# Ensure lock is released on exit (even if script crashes)
trap 'rm -rf "$LOCK_FILE"' EXIT

# Run full re-indexing in background
# --force: force re-validation of entire index (amend/rebase can change history)
# --quiet: suppress output (we're detached anyway)
nohup contextual index --force --quiet &

# Disown the background process so it survives shell exit
disown

# Always exit 0 so git never fails
exit 0
