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

# fake paru (unit tests; fakes/yay/yay runs this file as yay): replays the output of paru 2.1.0
# and yay 13.0.1 recorded in discovery/pacman.md section 15 (tests/unit/data/aur/) and logs every
# call, followed by "<helper> as: HOME=... PWD=... stdin=tty|notty" (where and how it runs).
# FAKE_AUR_QUA selects what -Qua prints: fixture (default: pfetch and su-dummy-aur), ignored
# (pfetch in IgnorePkg: paru marks it [ignored], yay leaves it out), devel (a -git package whose
# upstream moved: "-> latest-commit"), dup (an AUR row for su-dummy-b, which a repository has),
# noise (yay's colored root warning on stdout), none (nothing to upgrade: exit 1, no output) or
# fail (the AUR is unreachable: exit 1 with the recorded error). Packages purged by the fake pacman
# are not listed. -Sia PKG prints data/aur/Sia-<helper>-PKG.txt (else the helper's not-found
# error, exit 1), twice with FAKE_AUR_SIA=twice (a record that cannot be merged), or the variant
# Sia-<helper>-PKG-<FAKE_AUR_SIA>.txt when it exists; -Sua exits FAKE_AUR_SUA_RC (default 0).
# claude-desktop: yay's record is the wrapped one yay prints without COLUMNS=0, recorded verbatim.
# shellcheck source=../fakelib.bash
. "${BASH_SOURCE[0]%/*}/../fakelib.bash"
fake_log "$@"
if [[ -t 0 ]]; then stdin='tty'; else stdin='notty'; fi
printf '%s as: HOME=%s PWD=%s stdin=%s\n' "$FAKE_NAME" "${HOME-}" "$PWD" "$stdin" >>"$FAKE_LOG"
D=$FAKE_DATA/aur

case ${1:-} in
-Qua)
	case ${FAKE_AUR_QUA:-fixture} in
	none) exit 1 ;;
	fail)
		cat "$D/Qua-fail-$FAKE_NAME.err" >&2
		exit 1
		;;
	esac
	out=$(
		while IFS= read -r line; do
			fake_purged "${line%% *}" || printf '%s\n' "$line"
		done <"$D/Qua-$FAKE_NAME-${FAKE_AUR_QUA:-fixture}.txt"
	)
	[[ -n $out ]] || exit 1
	printf '%s\n' "$out"
	;;
-Sia)
	if [[ -n ${FAKE_AUR_SIA:-} && -f $D/Sia-$FAKE_NAME-${2:-}-$FAKE_AUR_SIA.txt ]]; then
		cat "$D/Sia-$FAKE_NAME-$2-$FAKE_AUR_SIA.txt"
		exit 0
	fi
	if [[ -f $D/Sia-$FAKE_NAME-${2:-}.txt ]]; then
		cat "$D/Sia-$FAKE_NAME-$2.txt"
		[[ ${FAKE_AUR_SIA:-} != twice ]] || cat "$D/Sia-$FAKE_NAME-$2.txt"
		exit 0
	fi
	if [[ $FAKE_NAME == yay ]]; then
		echo " -> No AUR package found for ${2:-}" >&2
	else
		echo "error: package '${2:-}' was not found" >&2
	fi
	exit 1
	;;
-Sua) exit "$(fake_rc FAKE_AUR_SUA_RC 0)" ;;
*)
	echo "fake $FAKE_NAME: unhandled: $*" >&2
	exit 99
	;;
esac
