. "$BST_LIB"
require tclsh tcl/present

out=$(tclsh "$BST_DATA/selftest.tcl" 2>&1); rc=$?

# On the static glibc arm every Tcl tool SIGILLs during interp init: tclsh calls
# getpwuid() and glibc's NSS loader dlopen's a backend on the coroutine resume
# path, hitting `unreachable` at __nss_module_load.resume (rc>=128, no output).
# Tracked as brintos/linux-in-the-browser#92 (JIRA BRINTOS-77). musl has no
# NSS/dlopen and passes. Present-but-broken -> `not ok`, never skip.
BLOCK92="blocked: glibc NSS __nss_module_load SIGILL on static wasm32-hwjs - brintos#92 / BRINTOS-77"
rseen=$(printf '%s\n' "$out" | grep -c '^R[0-9]')
blocked=0
[ "$rc" -ge 128 ] && [ "$rseen" -eq 0 ] && blocked=1

# whole-suite gate
case "$out" in *ALL-TCL-OK*) all=1 ;; *) all=0 ;; esac
if [ "$rc" -eq 0 ] && [ "$all" -eq 1 ]; then bst_ok tcl/all-ok
elif [ "$blocked" -eq 1 ]; then bst_notok tcl/all-ok "$BLOCK92"
else bst_notok tcl/all-ok "rc=$rc $(_bst_1line "$out")"; fi

if [ "$blocked" -eq 1 ]; then
  # Tcl never started; the R-line assertions cannot run. Record them against the
  # blocker rather than emitting opaque per-case failures.
  for c in expr fib15 list string utf8 encodings; do bst_notok "tcl/$c" "$BLOCK92"; done
else
  # fine-grained assertions parsed from the payload's R-lines
  check_eq tcl/expr  42          "$(printf '%s\n' "$out" | awk '/^R2-expr/{print $2}')"
  check_eq tcl/fib15 610         "$(printf '%s\n' "$out" | awk '/^R2-fib15/{print $2}')"
  check_eq tcl/list  "1 2 3 10"  "$(printf '%s\n' "$out" | sed -n 's/^R2-list //p')"
  check_eq tcl/string "ABC/5"    "$(printf '%s\n' "$out" | awk '/^R2-string/{print $2}')"
  check_eq tcl/utf8  1           "$(printf '%s\n' "$out" | awk '/^R3-utf8/{print $2}')"

  # encoding count is environment-specific — assert a positive integer, not a literal
  encn=$(printf '%s\n' "$out" | awk '/^R1-encN/{print $2}')
  if [ -n "$encn" ] && [ "$encn" -gt 0 ] 2>/dev/null; then bst_ok tcl/encodings
  else bst_notok tcl/encodings "encN='$encn'"; fi
fi
