#!/usr/bin/env bash
# Mock `sudo`. NEVER elevates anything — a plain, unprivileged script like
# any other, exactly like Locke's uninstall.sh test harness's own `sudo`
# mock. Exists so install_launcher's `sudo install …` (and, if a test's
# fixtures don't already satisfy ensure_group, `sudo groupadd`/`sudo
# usermod`) are exercised for their DECISION — what argv did the script
# build? — without ever invoking a real privileged command.
#
# Logs every invocation (one line, the full argv) to $SONOMOS_TEST_SUDO_LOG,
# if set. Exit code is $SONOMOS_TEST_SUDO_EXIT, DEFAULT 1 (failure) — the
# realistic default for a sandbox with no real sudoers grant, and it avoids a
# misleading "succeeded with empty output" read on any code path this suite
# doesn't intend to exercise (e.g. `redirect_status`'s `sudo -n nft …`
# fallback). A test that wants a specific call to appear to succeed sets
# SONOMOS_TEST_SUDO_EXIT=0 for that run explicitly.
#
# SONOMOS_TEST_SUDO_EXEC=1 additionally RUNS the argv it was handed, as the
# ordinary unprivileged user, after stripping sudo's own leading flags. That is
# not an elevation of any kind — it is what lets a test exercise a code path
# whose EFFECT matters (the trust-store sweep must actually delete the anchor
# files it selected, and then verify they are gone) rather than only asserting
# on the argv the script built. Every path such a test touches is inside its
# own throwaway sandbox, because the script under test was pointed there by
# SONOMOS_TEST_ANCHOR_DIRS and friends. Default OFF, so no existing test's
# behaviour changes.
[ -n "${SONOMOS_TEST_SUDO_LOG:-}" ] && printf '%s\n' "$*" >> "$SONOMOS_TEST_SUDO_LOG"
if [ "${SONOMOS_TEST_SUDO_EXEC:-0}" = 1 ]; then
  while [ "$#" -gt 0 ]; do
    case "$1" in
      -n|-H|-E|-k) shift ;;
      -u) shift 2 ;;
      --) shift; break ;;
      -*) shift ;;
      *) break ;;
    esac
  done
  [ "$#" -gt 0 ] || exit 0
  exec "$@"
fi
exit "${SONOMOS_TEST_SUDO_EXIT:-1}"
