#!/bin/bash
# Get the log of a GitHub Actions workflow run using gh CLI
#
# Logs are long. Pass a grep pattern as the third argument to return only the
# matching lines with a little surrounding context, which is usually what a
# diagnosis needs. Note that secret values are masked by GitHub as ***, so a
# log cannot reveal one, but it does name the steps that consumed them.

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib.sh
source "$SCRIPT_DIR/lib.sh"

# Arguments
RUN_ID="$1"
FAILED_ONLY="${2:-false}"
PATTERN="$3"

# Validation
if [ -z "$RUN_ID" ]; then
    echo "Error: Missing run ID" >&2
    echo "Usage: $0 <run-id> [failed-only:true|false] [grep-pattern]" >&2
    echo "Run IDs come from get-runs.sh as the databaseId field" >&2
    exit 1
fi

# Check if gh is installed
if ! command -v gh &> /dev/null; then
    echo "Error: GitHub CLI (gh) is not installed" >&2
    exit 1
fi

# With a grep pattern, gh is piped into grep and a failed gh call makes grep
# match nothing, which this script reports as 'No lines matched' with exit 0.
# The guard catches the common cause, being run outside the repository. Any
# other gh failure still reads as a clean no-match; see the note in lib.sh.
require_repo_context

# Build command
if [ "$FAILED_ONLY" = "true" ]; then
    CMD="gh run view $RUN_ID --log-failed"
else
    CMD="gh run view $RUN_ID --log"
fi

# Execute, filtering to the pattern when one is given
if [ -n "$PATTERN" ]; then
    eval "$CMD" | grep -i -C 3 -- "$PATTERN" || {
        echo "No lines matched: $PATTERN" >&2
        exit 0
    }
else
    eval "$CMD"
fi
