#!/usr/bin/env bash
set -euo pipefail

workflow_name="${1:-}"
required_sha="${2:-}"
release_sha="${3:-}"
branch_filter="${BRANCH_FILTER:-main}"
max_attempts="${MAX_ATTEMPTS:-120}"
poll_seconds="${POLL_SECONDS:-30}"

if [[ -z "$workflow_name" || -z "$required_sha" || -z "$release_sha" ]]; then
  echo "usage: release-ancestry-gate.sh <workflow> <required-sha> <release-sha>" >&2
  exit 2
fi

git cat-file -e "${required_sha}^{commit}"
git cat-file -e "${release_sha}^{commit}"

for ((attempt = 1; attempt <= max_attempts; attempt += 1)); do
  if ! successful_shas="$(gh run list \
    --workflow "$workflow_name" \
    --branch "$branch_filter" \
    --status success \
    --limit 100 \
    --json headSha \
    --jq '.[].headSha')"; then
    echo "Could not read workflow runs." >&2
    exit 1
  fi

  while IFS= read -r run_sha; do
    [[ -n "$run_sha" ]] || continue
    git cat-file -e "${run_sha}^{commit}" 2>/dev/null || continue

    if git merge-base --is-ancestor "$required_sha" "$run_sha" \
      && git merge-base --is-ancestor "$run_sha" "$release_sha"; then
      echo "$workflow_name succeeded at $run_sha and covers $required_sha."
      exit 0
    fi
  done <<< "$successful_shas"

  if [[ "$attempt" -lt "$max_attempts" ]]; then
    sleep "$poll_seconds"
  fi
done

echo "Timed out waiting for $workflow_name to cover $required_sha." >&2
exit 1
