#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2026 Bryan Joshua Pedini

# fake rpm (unit tests): answers the queries skeptical-updater makes from data/rpm/db.bash
# shellcheck source=../fakelib.bash
. "${BASH_SOURCE[0]%/*}/../fakelib.bash"
# shellcheck source=../../data/rpm/db.bash
. "$FAKE_DATA/rpm/db.bash"
fake_log "$@"

installed() { [[ -n ${EVR[$1]:-} ]] && ! fake_purged "$1"; }
all=0 whatprov=0 list=0 qf=''
names=()
while (($#)); do
	case $1 in
	-q) ;;
	-qa) all=1 ;;
	-ql) list=1 ;;
	--whatprovides) whatprov=1 ;;
	--qf | --queryformat)
		qf=$2
		shift
		;;
	*) names+=("$1") ;;
	esac
	shift
done
rc=0
if ((all)); then
	for p in "${!EVR[@]}"; do
		installed "$p" || continue
		case $qf in
		*'%{NAME}.%{ARCH}'*)
			for v in ${EVR[$p]}; do
				printf '%s.%s\t%s\n' "$p" "${ARCH[$p]}" "$v"
			done
			;;
		*'%{REQUIRENAME}'*'%{=NAME}'*)
			while IFS= read -r r; do [[ -n $r ]] && printf '%s\t%s\n' "$r" "$p"; done <<<"${REQUIRES[$p]:-}"
			;;
		*) printf '%s\n' "$p" ;;
		esac
	done
	exit 0
fi
if ((whatprov)); then
	for cap in "${names[@]}"; do
		hit=0
		for p in "${!EVR[@]}"; do
			installed "$p" || continue
			if grep -qxF -- "$cap" <<<"${PROVIDES[$p]:-}"$'\n'"${FILES[$p]:-}"; then
				printf '%s\n' "$p"
				hit=1
			fi
		done
		if ((!hit)); then
			echo "no package provides $cap"
			rc=1
		fi
	done
	exit "$rc"
fi
for p in "${names[@]}"; do
	if ! installed "$p"; then
		echo "package $p is not installed"
		rc=1
		continue
	fi
	if ((list)); then
		if [[ -n ${FILES[$p]:-} ]]; then printf '%s\n' "${FILES[$p]}"; else echo "(contains no files)"; fi
		continue
	fi
	case $qf in
	*'%{REQUIRENAME}'*) [[ -z ${REQUIRES[$p]:-} ]] || printf '%s\n' "${REQUIRES[$p]}" ;;
	*'%{PROVIDENAME}'*) [[ -z ${PROVIDES[$p]:-} ]] || printf '%s\n' "${PROVIDES[$p]}" ;;
	*'%{SUMMARY}'*) printf '%s\n' "${SUMMARY[$p]:-dummy summary of $p}" ;;
	*) printf '%s-%s.%s\n' "$p" "${EVR[$p]##* }" "${ARCH[$p]}" ;;
	esac
done
exit "$rc"
