#!/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.
#

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

# Only trigger on main branch
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" != "main" ]; 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 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

        # Wait for git push to complete (parent process exits)
        while kill -0 $GIT_PUSH_PID 2>/dev/null; do
            sleep 0.5
        done

        # Small delay to ensure push is fully complete
        sleep 1

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

    # Disown so git push can exit cleanly
    disown

    break
done

# Allow push to proceed
exit 0
