dump_state() {
  echo "===== DEBUG STATE ====="
  echo "--- /etc/hosts ---"
  cat /etc/hosts || true

  echo "--- getent shadow root ---"
  getent shadow root || true

  echo "--- sudo timestamp dir /run/sudo/ts ---"
  ls -l /run/sudo/ts 2>/dev/null || true

if [ -n "$WORK" ]; then
  echo "--- stdout/stderr files ---"
  # glob is intended
  head -n-0 $WORK/* || true
fi
}

assert_contains() {
  file="$1"
  shift
  for s in "$@"; do
    grep -F "$s" "$file" >/dev/null || {
      echo "missing: $s in $file"
      dump_state
      exit 1
    }
  done
}

assert_var() {
  var="$1"
  val="$2"
  expected="$3"

  if [ "$val" != "$expected" ]; then
    echo "ASSERT FAILED: expected $var = '$expected', got '$val'" >&2
    dump_state
    exit 1
  fi
}

reset_test() {
  deluser "$1" || true
  if [ -n "$2" ] ; then
    rm -rf "$2"
  fi
  adduser --disabled-password --home "$2" --gecos "" "$1"
  printf "%s:%s\n" "$1" "$3" | chpasswd
  if [ -n "$4" ]; then
    adduser "$1" "$4"
  fi
  sudo -k
  # glob intended here
  if [ -n "$STDOUTSTDERR" ]; then
    rm -f $STDOUTSTDERR
  fi
}
