#!/usr/bin/env bash
# Mock 'visudo' for linux.sh's test harnesses — a hard-fail tripwire BY
# DEFAULT. Most suites stay within install_launcher / launcher_status /
# ca-trust, and nothing there should ever reach 'visudo'; if this fires there,
# a test is exercising more of linux.sh than intended.
#
# SONOMOS_TEST_VISUDO_OK=1 opts into the one legitimate exception:
# sudo_home_test.sh drives `install-redirect-helper` — the very command whose
# wrong-home CA generation this whole change exists to fix — and that verb
# validates its generated drop-in with `visudo -cf <file>` before installing
# it. Answering 0 for THAT form only (a syntax check on a file, which writes
# nothing) keeps the tripwire everywhere else.
#
# SONOMOS_TEST_VISUDO_FAIL makes one kind of `-cf` check fail the way a syntax
# error does, so first_time_setup_test.sh can prove both of linux.sh's
# validations are load-bearing:
#   candidate — a file OUTSIDE the sudoers.d the sandbox names (the generated
#               rule, before it is written anywhere sudo looks);
#   installed — a file INSIDE it (the rule as installed, before it goes live).
# SONOMOS_TEST_VISUDO_LOG, when set, records every invocation.
[ -n "${SONOMOS_TEST_VISUDO_LOG:-}" ] && printf '%s\n' "$*" >> "$SONOMOS_TEST_VISUDO_LOG"
if [ "${SONOMOS_TEST_VISUDO_OK:-0}" = 1 ] && [ "$1" = "-cf" ]; then
  sudoers_dir="$(dirname "${SONOMOS_TEST_HELPER_SUDOERS:-/etc/sudoers.d/sonomos-redirect}")"
  case "$2" in
    "$sudoers_dir"/*) inside=1 ;;
    *) inside=0 ;;
  esac
  case "${SONOMOS_TEST_VISUDO_FAIL:-}" in
    candidate) if [ "$inside" = 0 ]; then echo ">>> $2: syntax error near line 1 <<<" >&2; exit 1; fi ;;
    installed) if [ "$inside" = 1 ]; then echo ">>> $2: syntax error near line 1 <<<" >&2; exit 1; fi ;;
  esac
  exit 0
fi
echo "MOCK-visudo: refusing unexpected invocation: $*" >&2
exit 97
