#!/bin/bash
#
# Pre-push hook: Spawns post-push release pipeline
#
# This hook:
# 1. Validates we're pushing to main
# 2. Spawns a background process that waits for push to complete
# 3. After push completes, the background process runs the release pipeline
#
# This gives us "post-push" behavior using only native git hooks.
#
# NOTE: Only triggers in interactive terminals. Automated pushes (daemons, CI)
# skip the post-push pipeline to avoid process detection issues.
#

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
INFRA_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Only trigger on main branch
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" != "main" ]; then
    exit 0
fi

# Skip post-push pipeline in non-interactive contexts (daemons, CI, scripts)
# The $PPID detection doesn't work reliably without a TTY
if [ ! -t 0 ] && [ ! -t 1 ]; then
    exit 0
fi

# Read push info from stdin to verify this is a real push
# Format: <local ref> <local sha> <remote ref> <remote sha>
while read local_ref local_sha remote_ref remote_sha; do
    # Only proceed if pushing to main
    if [[ "$remote_ref" != *"main"* ]]; then
        continue
    fi

    echo "Pre-push: Will trigger infrastructure release pipeline after push completes..."

    # Spawn background process that waits for push to complete
    (
        # Get parent PID (the git push process)
        GIT_PUSH_PID=$PPID

        # Safety timeout: max 60 seconds wait for push to complete
        TIMEOUT=120
        ELAPSED=0

        # Wait for git push to complete (parent process exits)
        while kill -0 $GIT_PUSH_PID 2>/dev/null; do
            sleep 0.5
            ELAPSED=$((ELAPSED + 1))
            if [ $ELAPSED -ge $TIMEOUT ]; then
                echo "Pre-push: Timeout waiting for push to complete, aborting post-push"
                exit 1
            fi
        done

        # Small delay to ensure push is fully complete
        sleep 1

        # Now run the post-push pipeline
        echo ""
        echo "Push complete. Starting infrastructure release pipeline..."
        "$SCRIPT_DIR/post-push"
    ) &

    # Disown so git push can exit cleanly
    disown

    break
done

# Allow push to proceed
exit 0
