#!/bin/bash
# ci-pipeline-wait.sh - Wait for Woodpecker CI pipeline completion
# Usage: ci-pipeline-wait.sh -n <pipeline_num> [-r <repo>] [-t <timeout>]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/detect-platform.sh"

# Parse arguments
REPO=""
PIPELINE_NUM=""
TIMEOUT=1800  # 30 minutes default
POLL_INTERVAL=10  # 10 seconds

show_help() {
    cat << EOF
Usage: ci-pipeline-wait.sh [OPTIONS]

Wait for a Woodpecker CI pipeline to complete.

Options:
  -n, --number <num>       Pipeline number (required)
  -r, --repo <owner/repo>  Repository (default: auto-detect from git remote)
  -t, --timeout <seconds>  Timeout in seconds (default: 1800)
  -i, --interval <seconds> Poll interval in seconds (default: 10)
  -h, --help               Show this help

Environment:
  WOODPECKER_SERVER        Woodpecker server URL (required)
  WOODPECKER_TOKEN         Woodpecker API token (required)

Exit codes:
  0 - Pipeline succeeded
  1 - Error or timeout
  2 - Pipeline failed
  3 - Pipeline killed/cancelled

Examples:
  # Wait for pipeline 42 to complete
  ci-pipeline-wait.sh -n 42

  # Wait with custom timeout (10 minutes)
  ci-pipeline-wait.sh -n 42 -t 600
EOF
}

while [[ $# -gt 0 ]]; do
    case $1 in
        -r|--repo)
            REPO="$2"
            shift 2
            ;;
        -n|--number)
            PIPELINE_NUM="$2"
            shift 2
            ;;
        -t|--timeout)
            TIMEOUT="$2"
            shift 2
            ;;
        -i|--interval)
            POLL_INTERVAL="$2"
            shift 2
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# Validate required arguments
if [[ -z "$PIPELINE_NUM" ]]; then
    echo "Error: Pipeline number is required (-n)"
    show_help
    exit 1
fi

# Check required environment variables
if [[ -z "$WOODPECKER_SERVER" ]]; then
    echo "Error: WOODPECKER_SERVER environment variable not set"
    exit 1
fi

if [[ -z "$WOODPECKER_TOKEN" ]]; then
    echo "Error: WOODPECKER_TOKEN environment variable not set"
    exit 1
fi

# Auto-detect repo if not provided
if [[ -z "$REPO" ]]; then
    REPO=$(get_repo_info)
    if [[ $? -ne 0 ]]; then
        echo "Error: Could not auto-detect repository. Use -r option."
        exit 1
    fi
fi

# Check if woodpecker CLI is installed
if ! command -v woodpecker &> /dev/null; then
    echo "Error: woodpecker CLI not found. Install it first:"
    echo "  Arch: paru -S woodpecker"
    echo "  Other: https://woodpecker-ci.org/docs/usage/cli"
    exit 1
fi

echo "Waiting for pipeline #$PIPELINE_NUM in $REPO (timeout: ${TIMEOUT}s)..."

elapsed=0
while [[ $elapsed -lt $TIMEOUT ]]; do
    # Get pipeline info
    pipeline_info=$(woodpecker pipeline info "$REPO" "$PIPELINE_NUM" 2>&1)

    # Extract status from output
    # Woodpecker CLI outputs status in format like "STATUS: success"
    if echo "$pipeline_info" | grep -q "success"; then
        echo "✓ Pipeline succeeded"
        exit 0
    elif echo "$pipeline_info" | grep -q "failure\|error"; then
        echo "✗ Pipeline failed"
        echo ""
        echo "$pipeline_info"
        exit 2
    elif echo "$pipeline_info" | grep -q "killed\|cancelled"; then
        echo "✗ Pipeline was cancelled"
        echo ""
        echo "$pipeline_info"
        exit 3
    elif echo "$pipeline_info" | grep -q "pending\|running"; then
        # Still running
        echo -n "."
        sleep "$POLL_INTERVAL"
        elapsed=$((elapsed + POLL_INTERVAL))
    else
        # Unknown status, show info and continue
        echo ""
        echo "Unknown status, continuing to wait..."
        echo "$pipeline_info"
        sleep "$POLL_INTERVAL"
        elapsed=$((elapsed + POLL_INTERVAL))
    fi
done

echo ""
echo "✗ Timeout after ${TIMEOUT}s"
exit 1
