#!/bin/bash
# Print the PR build matrix for a set of package directories as JSON: one
# entry per package per supported architecture. Every package builds exactly
# once, against edge, and that one artifact is what every channel ships:
# channels are databases over a shared pool of files, and a filename must
# mean one set of bytes. "channels" lists where the artifact is published on
# merge: edge for everything, plus rc and stable immediately for the fast
# ring. Eligibility comes from package_builds_for_mirror, the rule the
# release host uses, so CI and the host cannot disagree.
#
# Usage: build-matrix [--arch <arch>|all] <package>...
#   Reads package names on stdin when none are given. With no --arch, every
#   architecture in CI_ARCHES (default "x86_64 aarch64") the package supports.
#   Output: {"include":[{"package":"x","arch":"x86_64","channels":"edge rc stable","publish_arches":"x86_64"},...]}
#   arch is where it builds; publish_arches lists every architecture
#   database the file goes into (all of them for arch=any).
set -euo pipefail
BUILD_ROOT=$(realpath "${BASH_SOURCE[0]%/*}/..")
source "$BUILD_ROOT/helpers/paths.sh"
source "$BUILD_ROOT/helpers/package-metadata.sh"

ARCHES=$CI_ARCHES
if [[ "${1:-}" == --arch ]]; then [[ $2 == all ]] || ARCHES=$2; shift 2; fi
for a in $ARCHES; do require_valid_arch "$a"; done

if (( $# )); then names=("$@"); else mapfile -t names; fi

entries=()
for name in "${names[@]}"; do
  [[ -n "$name" ]] || continue
  pkgdir="$PKGBUILDS_DIR/$name"
  [[ -d "$pkgdir" ]] || continue
  # skip_build packages still build on their own PR (explicit --package
  # semantics); the host's unscoped runs are what skip them.
  channels=""
  for mirror in $VALID_MIRRORS; do
    package_builds_for_mirror "$pkgdir" "$mirror" && channels="$channels $mirror"
  done
  channels=${channels# }
  [[ -n "$channels" ]] || continue
  # An arch=any package produces one architecture-independent file, so it
  # builds once, on the first architecture, and that file serves every
  # channel database of every architecture.
  if [[ " $(package_arches "$pkgdir" "${ARCHES%% *}") " == *" any "* ]]; then
    entries+=("$(jq -nc --arg p "$name" --arg a "${ARCHES%% *}" --arg c "$channels" --arg pa "$ARCHES" '{package:$p, arch:$a, channels:$c, publish_arches:$pa}')")
    continue
  fi
  for arch in $ARCHES; do
    package_supports_arch "$pkgdir" "$arch" || continue
    entries+=("$(jq -nc --arg p "$name" --arg a "$arch" --arg c "$channels" '{package:$p, arch:$a, channels:$c, publish_arches:$a}')")
  done
done

printf '%s\n' "${entries[@]}" | jq -sc '{include: .}'
