#!/usr/bin/env bash
set -euo pipefail

# miaur — pure-shell AUR helper (paru-like daily workflow)

MIAUR_HOME=$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)

# shellcheck source=lib/common.sh
source "$MIAUR_HOME/lib/common.sh"
# shellcheck source=lib/config.sh
source "$MIAUR_HOME/lib/config.sh"
# shellcheck source=lib/aur_rpc.sh
source "$MIAUR_HOME/lib/aur_rpc.sh"
# shellcheck source=lib/clone.sh
source "$MIAUR_HOME/lib/clone.sh"
# shellcheck source=lib/review.sh
source "$MIAUR_HOME/lib/review.sh"
# shellcheck source=lib/deps.sh
source "$MIAUR_HOME/lib/deps.sh"
# shellcheck source=lib/build.sh
source "$MIAUR_HOME/lib/build.sh"
# shellcheck source=lib/upgrade.sh
source "$MIAUR_HOME/lib/upgrade.sh"
# shellcheck source=lib/cli.sh
source "$MIAUR_HOME/lib/cli.sh"
# shellcheck source=lib/dispatch.sh
source "$MIAUR_HOME/lib/dispatch.sh"

main() {
	miaur_load_config

	# Fast path: operations that are pure pacman wrappers with no AUR flags
	# Keep original argv for -R/-D/-F/-T/-U when no miaur-specific long opts mixed in awkwardly.
	# We still parse to detect them.
	local -a orig=("$@")
	parse_args "$@"

	# Special: if DO_PASSTHRU and OP empty, forward entire original command
	if [[ $DO_PASSTHRU -eq 1 && -z ${OP:-} ]]; then
		# Replace program name conceptually — strip miaur-only long options already consumed
		as_root ${MIAUR_PACMAN} "${orig[@]}"
		return $?
	fi

	# For -R with extras like -Rns: OP=R DO_PASSTHRU=1
	if [[ ${OP:-} == R ]]; then
		local -a rargs=(-R)
		local c
		for c in "${PACMAN_EXTRA[@]}"; do
			rargs+=("-$c")
		done
		rargs+=("${TARGETS[@]}")
		as_root ${MIAUR_PACMAN} "${rargs[@]}"
		return $?
	fi

	dispatch
}

main "$@"
