#!/usr/bin/env bash
# Regression test for the read-only system installs dir scenario:
# When tools are installed in a system dir that the current user cannot
# write to (e.g. a Docker image where root installed at build time and a
# non-root user runs `mise install` at runtime), `mise install` of an
# unrelated tool must NOT try to rewrite the system dir's runtime symlinks.
# https://github.com/jdx/mise/discussions/8596

export MISE_SYSTEM_DATA_DIR="$HOME/.local/share/mise-system"
SYSTEM_INSTALLS="$MISE_SYSTEM_DATA_DIR/installs"
USER_INSTALLS="$MISE_DATA_DIR/installs"

# Install one version to user dir and another to "system" dir.
mise install tiny@1.0.0
mise install --system tiny@2.1.0

# Sanity: both got their `latest` symlinks.
assert "readlink $USER_INSTALLS/tiny/latest" "./1.0.0"
assert "readlink $SYSTEM_INSTALLS/tiny/latest" "./2.1.0"

# Drop write access to the system dir to simulate the "root-owned, non-root
# runtime" Docker pattern. Trap restores write access so the harness can
# clean up the test dir.
chmod -R a-w "$SYSTEM_INSTALLS"
trap 'chmod -R u+w "$SYSTEM_INSTALLS" 2>/dev/null || true' EXIT

assert_silent_install() {
	local out
	if ! out="$($1 2>&1)"; then
		echo "$out"
		fail "[$1] command failed"
	fi
	echo "$out"
	if [[ $out == *"skipping symlink update"* || $out == *"Permission denied"* || $out == *"failed rm"* ]]; then
		fail "[$1] unexpected system-dir warning during install"
	fi
}

# Re-installing a tool that lives only in the user dir must succeed without
# any warning about the system dir — the system-side runtime symlink already
# matches the desired state, so nothing should be written or attempted there.
assert_silent_install "mise install --force tiny@1.0.0"
assert "readlink $USER_INSTALLS/tiny/latest" "./1.0.0"
assert "readlink $SYSTEM_INSTALLS/tiny/latest" "./2.1.0"

# Installing a different tool that doesn't touch the system dir at all must
# also succeed silently.
assert_silent_install "mise install dummy@1.0.0"
assert_directory_exists "$USER_INSTALLS/dummy/1.0.0"
assert "readlink $SYSTEM_INSTALLS/tiny/latest" "./2.1.0"
