#!/bin/sh
# One dispatcher; every fake in this directory is a symlink to it.
#
# The old version of this file did two things wrong, and both let real bugs
# through:
#
#   it always succeeded    so no test could ever reach an installer's failure
#                          path -- the apt and npm one-at-a-time retries, the
#                          "did not install" report, and cmd_install's non-zero
#                          exit were all unreachable, and all three survived
#                          being deleted outright.
#   it failed OPEN         the fakes were PREPENDED to $PATH, so a package
#                          manager with no fake here fell through to the real
#                          one. An audit of this suite invoked the host's real
#                          `brew`. A fake that is missing must be an ERROR, not
#                          a silent hand-off to the machine.
#
# The second is fixed by seal.sh, which builds a directory holding exactly the
# tools a run may touch -- fakes for anything that installs, downloads or needs
# root, real binaries for the pure ones -- and runs dotup under `env -i` with
# that directory as the WHOLE of PATH. Anything not listed is command-not-found.
#
# ---------------------------------------------------------------- failure ---
# FAKE_FAIL is a comma-separated list of injections:
#
#   FAKE_FAIL=brew              brew exits 1 every time
#   FAKE_FAIL=apt-get:batch     apt-get fails only when asked for >1 package,
#                               which is what a real "unable to locate package"
#                               inside a batch looks like: the batch dies and
#                               the one-at-a-time retry is the only thing that
#                               saves the other thirty.
#   FAKE_FAIL=npm:batch         the same shape for npm.
#   FAKE_FAIL=curl:deb          curl fails only for the .deb download.
#   FAKE_FAIL=curl:docker       curl fails only for the get.docker.com script.
#                               That is how the docker group's failure path is
#                               reached: one note_fail, nothing executed, and
#                               the other two rows reported as not attempted.
#
# Several may be combined: FAKE_FAIL=brew,apt-get:batch
set -u
me=${0##*/}
printf '%s %s\n' "$me" "$*" >> "${DOTUP_TEST_LOG:?DOTUP_TEST_LOG unset}"

# The mode this run injects for THIS tool: "always", a tool-specific word, or
# empty for "behave".
mode=
_oldifs=$IFS
IFS=,
for _e in ${FAKE_FAIL:-}; do
	case $_e in
	"$me")   mode=always; break ;;
	"$me":*) mode=${_e#*:}; break ;;
	esac
done
IFS=$_oldifs
[ "$mode" = always ] && exit 1

# Count the package-ish arguments of a batch call: everything after the
# subcommand that is not a flag and not the flag's value.
count_pkgs() {
	n=0
	for a in "$@"; do
		case $a in
		-*|install|update|show|get|tool|-g|-y|--*) continue ;;
		*=*) continue ;;
		esac
		n=$((n + 1))
	done
	printf '%s\n' "$n"
}

case $me in
apt-get)
	case ${1:-} in update) exit 0 ;; esac
	[ "$mode" = batch ] && [ "$(count_pkgs "$@")" -gt 1 ] && exit 1
	exit 0 ;;
npm)
	[ "$mode" = batch ] && [ "$(count_pkgs "$@")" -gt 1 ] && exit 1
	exit 0 ;;
apt-cache)
	# Stand in for a real apt cache. Two names are special, and both are real
	# behaviours of stock Ubuntu that the installer has to tell apart:
	#
	#   gh         genuinely absent -- `apt-cache policy` prints nothing. The
	#              manifest's real example of a name that falls through to brew.
	#   nvidia-container-toolkit
	#              present in the cache but with `Candidate: (none)`: it is
	#              published from NVIDIA's own repository, which nothing here
	#              configures. `apt-cache show` exits 0 for this, which is why
	#              the old probe kept it in the batch and let apt refuse all
	#              thirty packages at once. (docker-ce used to be this example;
	#              the docker rows install from get.docker.com now and never
	#              reach apt at all, so the live case is NVIDIA's.)
	case ${1:-} in
	policy)
		case ${2:-} in
		gh) exit 0 ;;
		nvidia-container-toolkit) printf '%s:\n  Installed: (none)\n  Candidate: (none)\n' "$2"; exit 0 ;;
		esac
		printf '%s:\n  Installed: (none)\n  Candidate: 1.0-fake\n' "$2"; exit 0 ;;
	esac
	case ${2:-} in gh) exit 100 ;; esac
	printf 'Package: %s\n' "${2:-}"; exit 0 ;;
unzip)
	# `unzip -oq <zip> -d <dir>` -- produce the one member ensure_bws looks for.
	d=; prev=
	for a in "$@"; do [ "$prev" = -d ] && { d=$a; break; }; prev=$a; done
	[ -n "$d" ] || exit 1
	mkdir -p "$d" && printf '#!/bin/sh\necho "bws 2.1.0"\n' > "$d/bws" \
		&& chmod 755 "$d/bws" && exit 0
	exit 1 ;;
dpkg)
	# install_deb fills %a in a gh: asset name from this.
	case ${1:-} in --print-architecture) echo amd64 ;; esac
	exit 0 ;;
chezmoi)
	# `chezmoi init --apply --source DIR -c CFG URL`. Produce the shape the
	# caller checks for -- a source tree with a .git in it -- and NOTHING else,
	# at the caller's umask, so a missing `chmod -R go-rwx` is visible as a mode.
	src=; prev=
	for a in "$@"; do [ "$prev" = --source ] && { src=$a; break; }; prev=$a; done
	[ -n "$src" ] || exit 0
	mkdir -p "$src/.git" && : > "$src/.git/config" && : > "$src/README" || exit 1
	exit 0 ;;
curl) . "$(dirname "$0")/_curl" ;;
gpg)
	# `gpg --show-keys --with-colons KEY`: one fpr record. FAKE_GPG_FPR stands in
	# for a key that is not the one Anthropic publishes.
	printf 'pub:-:4096:1:BAA929FF1A7ECACE:0:::-:::scESC::::::23::0:\n'
	printf 'fpr:::::::::%s:\n' "${FAKE_GPG_FPR:-31DDDE24DDFAB679F42D7BD2BAA929FF1A7ECACE}"
	exit 0 ;;
go)
	# `go env GOBIN` is empty and GOPATH is ~/go, which is the stock layout.
	# `go install MOD@latest` drops a fake of the module's last segment in
	# ~/go/bin, so a second run can see it. FAKE_FAIL=go:install fails them.
	case ${1:-} in
	env) case ${2:-} in GOPATH) echo "$HOME/go" ;; esac; exit 0 ;;
	install)
		[ "$mode" = install ] && exit 1
		t=${2%@*}; t=${t##*/}
		mkdir -p "$HOME/go/bin" && ln -sf "$(dirname "$0")/_fake" "$HOME/go/bin/$t"
		exit 0 ;;
	esac
	exit 0 ;;
herdr)
	# `herdr integration status` lists one `<agent>: <state> (...)` line per
	# integration; FAKE_HERDR_CURRENT names the agents to report `current`,
	# every other one is `not installed`. The paths are the real ones' shape.
	# `install` writes nothing, but like the real herdr it fails when the
	# target's directory is missing: herdr does not create ~/.omp/agent/extensions.
	_herdr_target() {
		case $1 in
		pi)     echo "$HOME/.pi/agent/extensions/herdr-agent-state.ts" ;;
		omp)    echo "$HOME/.omp/agent/extensions/herdr-omp-agent-state.ts" ;;
		claude) echo "$HOME/.claude/hooks/herdr-agent-state.sh" ;;
		codex)  echo "$HOME/.codex/herdr-agent-state.sh" ;;
		*)      echo "$HOME/.$1/hooks/herdr-agent-state.sh" ;;
		esac
	}
	case ${1:-}:${2:-} in
	integration:status)
		for _a in pi omp claude codex copilot; do
			case " ${FAKE_HERDR_CURRENT:-} " in
			*" $_a "*) printf '%s: current (v11) (%s)\n' "$_a" "$(_herdr_target "$_a")" ;;
			*)         printf '%s: not installed (%s)\n' "$_a" "$(_herdr_target "$_a")" ;;
			esac
		done ;;
	integration:install)
		[ "$mode" = install ] && exit 1
		_t=$(_herdr_target "${3:-}")
		[ -d "${_t%/*}" ] || { echo "error: ${_t%/*}: No such file or directory" >&2; exit 1; } ;;
	esac
	exit 0 ;;
nvim)
	# Behaves like lazy.nvim's first start: a plain boot creates the plugin
	# directory and REWRITES lazy-lock.json with drifted commits, which is the
	# bug the installer's first-boot step exists to undo. `+Lazy! restore`
	# records the lockfile it was handed in ~/.nvim-restored-from. Injections:
	# FAKE_FAIL=nvim:boot and FAKE_FAIL=nvim:restore.
	_lock=${XDG_CONFIG_HOME:-$HOME/.config}/nvim/lazy-lock.json
	case "$*" in
	*'Lazy! restore'*)
		[ "$mode" = restore ] && exit 1
		cp "$_lock" "$HOME/.nvim-restored-from"; exit 0 ;;
	esac
	mkdir -p "${XDG_DATA_HOME:-$HOME/.local/share}/nvim/lazy/lazy.nvim"
	[ -f "$_lock" ] && printf '{ "drifted": "tip" }\n' > "$_lock"
	[ "$mode" = boot ] && exit 1
	exit 0 ;;
fzf)
	# The picker's own fzf, and the only fake here whose ARGV is the thing
	# under test. `--bind` strings are built across a dozen continued lines, so
	# one stray comment between them silently truncates the command and the
	# picker draws with two binds instead of seven. Dump argv one argument per
	# line -- a bind that lost its continuation cannot masquerade as one that
	# survived -- and behave like an accept: read the piped rows, print nothing.
	case ${1:-} in --version) echo "${FAKE_FZF_VERSION:-9.9.9} (fake)"; exit 0 ;; esac
	[ -n "${FAKE_FZF_ARGV:-}" ] && printf '%s\n' "$@" > "$FAKE_FZF_ARGV"
	cat > /dev/null
	exit "${FAKE_FZF_RC:-0}" ;;
esac
exit 0
