#!/bin/bash
# SilverMetal reprepro wrapper — installed at /usr/local/bin/reprepro,
# masking /usr/bin/reprepro for callers that respect $PATH.
#
# Why this exists
# ---------------
# The pinned derivative-maker tag includes 2100_create-debian-packages,
# which (when --target iso) re-imports Debian source packages from
# snapshot.debian.org into a local apt repo via:
#     reprepro --basedir … includedsc local <some>.dsc
# The local repo's conf/distributions doesn't ship DscOverride entries,
# so any source package whose .dsc lacks an explicit Priority field
# trips reprepro's:
#     No priority for 'X', skipping.
#     There have been errors!
# and reprepro exits 255. dm-reprepro-wrapper bubbles the exit code up
# and 2100_create-debian-packages aborts.
#
# This is the situation for virtualbox_*.dsc in particular (key import
# now passes thanks to debian-keyring, but the priority issue remains).
# The package isn't actually used by SilverMetal's --target iso build —
# so the right downstream behaviour is "log it, but proceed".
#
# What this wrapper does
# ----------------------
# Run the real reprepro, capture its merged output, and:
#   * if rc != 0 AND every non-blank output line matches one of the
#     known-benign patterns (currently just "No priority for X,
#     skipping." plus the trailing "There have been errors!"),
#     emit the output verbatim, log a single line to stderr, and
#     exit 0.
#   * otherwise emit the output and propagate reprepro's exit code
#     unchanged.
#
# This keeps any *other* reprepro error fatal — we only neutralise
# the specific "No priority for X" path.

set -uo pipefail

REAL=/usr/bin/reprepro

# Run real reprepro, capture merged stdout+stderr.
output=$("$REAL" "$@" 2>&1)
rc=$?

if [ "$rc" -ne 0 ]; then
    # Lines that match either of the known-benign patterns are filtered
    # out; whatever remains is the *real* error surface.
    remaining=$(printf '%s\n' "$output" \
        | grep -vE "^No priority for '[^']+', skipping\.$" \
        | grep -vE '^There have been errors!$' \
        | grep -vE '^$' || true)

    if [ -z "$remaining" ]; then
        printf '%s\n' "$output"
        printf '\n[silvermetal-reprepro-wrap] Only benign "No priority for" errors; treating exit %d as 0.\n' "$rc" >&2
        exit 0
    fi
fi

printf '%s\n' "$output"
exit "$rc"
