#!/usr/bin/env bash
# Checks the AUR carries the versions a release tag published, reading each wanted pkgrel from the tag's own PKGBUILDs.
set -uo pipefail

json_file=""
if [ "${1:-}" = "--json" ]; then
    [ -n "${2:-}" ] || { echo "flea-aur-versions: --json needs a file" >&2; exit 2; }
    json_file=$2
    shift 2
fi
[ "$#" -eq 2 ] || { echo "usage: flea-aur-versions [--json FILE] X.Y.Z COMMIT" >&2; exit 2; }
version=$1
commit=$2
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "flea-aur-versions: '$version' is not X.Y.Z" >&2; exit 2; }
[[ "$commit" =~ ^[0-9a-f]{7,40}$ ]] || { echo "flea-aur-versions: commit must be 7 to 40 hex digits" >&2; exit 2; }
short=${commit:0:7}

. "$(dirname "$0")/flea-pkgrel-field"

# The wanted pkgrel comes from the tag commit's own PKGBUILD, failing closed outside a checkout.
want_rel() {
  local value
  value=$(field "$commit" "$1" pkgrel) || {
    echo "flea-aur-versions: cannot read pkgrel from $1 at $commit" >&2
    exit 2
  }
  printf '%s' "$value"
}
flea_rel=$(want_rel packaging/flea/PKGBUILD) || exit 2
bin_rel=$(want_rel packaging/flea-bin/PKGBUILD) || exit 2

if [ -n "$json_file" ]; then
    [ -f "$json_file" ] || { echo "flea-aur-versions: no file at '$json_file'" >&2; exit 2; }
    reply=$(cat -- "$json_file")
else
    # Same bounds src/update.rs uses: ten seconds and one mebibyte.
    reply=$(curl -q --silent --fail --globoff --max-time 10 --max-filesize 1M \
        'https://aur.archlinux.org/rpc/v5/info?arg[]=flea&arg[]=flea-bin&arg[]=flea-git') \
        || { echo "flea-aur-versions: the AUR RPC could not be read" >&2; exit 1; }
fi

# Sample input: {"results":[{"Name":"flea","Version":"0.3.7-1"}]}
listed=$(printf '%s' "$reply" | python3 -c '
import json, sys
try:
    doc = json.load(sys.stdin)
    rows = doc.get("results", [])
    for r in rows:
        print("%s\t%s" % (r.get("Name", ""), r.get("Version", "")))
except Exception as e:
    sys.stderr.write("flea-aur-versions: the RPC reply did not parse: %s\n" % e)
    sys.exit(1)
') || exit 1

failed=0
# Sample input: flea<TAB>0.3.7-1
check() {
    local name=$1 want=$2 got
    got=$(printf '%s\n' "$listed" | awk -F'\t' -v n="$name" '$1 == n { print $2; exit }')
    if [ "$got" = "$want" ]; then
        printf '%s: ok %s\n' "$name" "$got"
    elif [ -z "$got" ]; then
        printf '%s: MISMATCH missing from the AUR reply, want %s\n' "$name" "$want"
        failed=1
    else
        printf '%s: MISMATCH got %s, want %s\n' "$name" "$got" "$want"
        failed=1
    fi
}
check flea "$version-$flea_rel"
check flea-bin "$version-$bin_rel"
check flea-git "$version.r0.g$short-1"
exit "$failed"
