#!/usr/bin/env bash
# check whether packages that should be kept in sync are up-to-date
# (c) 2023-2026 Michał Górny <mgorny@gentoo.org>
# SPDX-License-Identifier: GPL-2.0-or-later

REPO=$(git rev-parse --show-toplevel)

# A=B where all slots of A are tested
PKGS=()

cd "${REPO}" || exit 1
for PKG in dev-python/ensurepip-*; do
	PKGS+=( "${PKG}=${PKG/ensurepip-}" )
done

PKGS+=(
	app-doc/python-docs=dev-lang/python
	dev-python/python-tests=dev-lang/python
	dev-python/uv=dev-python/uv-build
)

declare -A VERSIONS SLOTS
while read -r PKG; do
	SLOT=${PKG#*:}
	PKG=${PKG%:*}
	PKG=${PKG%-r[0-9]*}
	NAME=${PKG%-*}
	VERSION=${PKG##*-}
	VERSION=${VERSION%_p*}
	# ignore live ebuilds, we want to check newest release
	[[ ${VERSION} == *9999* ]] && continue
	VERSIONS[${NAME}:${SLOT}]=${VERSION}
	if [[ ${SLOTS[${NAME}]} != *" ${SLOT} " ]]; then
		SLOTS[${NAME}]+=" ${SLOT} "
	fi
done < <(
	pquery --raw --quiet --repo "${REPO}" --slot "${PKGS[@]%=*}" "${PKGS[@]#*=}"
)

RET=0
for PKG in "${PKGS[@]}"; do
	A=${PKG%=*}
	B=${PKG#*=}

	for SLOT in ${SLOTS[${A}]}; do
		AS=${A}:${SLOT}
		BS=${B}:${SLOT}
		AV="${VERSIONS[${AS}]}"
		BV="${VERSIONS[${BS}]}"

		if [[ ${AV} != ${BV} ]]; then
			echo "Package version mismatch found!" >&2
			echo "  ${AS}: ${AV}" >&2
			echo "  ${BS}: ${BV}" >&2
			RET=1
		fi
	done
done

exit "${RET}"
