#!/bin/sh
# brintos-selftest — run the on-target brintOS package self-tests and emit a
# machine-parseable report. POSIX sh (busybox ash); the target image has no bash.
#
# Usage: brintos-selftest [suite ...]
#   With no args, runs every tests/*.test. Each arg is a substring that selects
#   matching test files (e.g. `brintos-selftest tcl net` runs *tcl*.test + *net*.test).
#
# Output protocol (consumed by brintos_browser_verify --runner):
#   ==BST-BEGIN==
#   BST ok     <suite>/<case>
#   BST not ok <suite>/<case> : <detail>
#   BST skip   <suite>/<case> : <reason>
#   ==BST-SUMMARY pass=<N> fail=<N> skip=<N> total=<N>==
#   ==BST-END==
# The BEGIN/END sentinels bracket the run so a truncated or hung run is
# detectable. Exit status is 0 iff fail==0.

BST_DIR=${BST_DIR:-/usr/lib/brintos-tests}
BST_TESTS="$BST_DIR/tests"
export BST_DIR
export BST_DATA="${BST_DATA:-$BST_DIR/data}"
export BST_LIB="${BST_LIB:-$BST_DIR/lib/bst.sh}"

pass=0; fail=0; skip=0

run_one() {   # $1 = path to a .test file
  _out=$(sh "$1" 2>&1)          # own shell → a crashing test loses only its own cases
  printf '%s\n' "$_out"
  _p=$(printf '%s\n' "$_out" | grep -c '^BST ok ')
  _f=$(printf '%s\n' "$_out" | grep -c '^BST not ok ')
  _s=$(printf '%s\n' "$_out" | grep -c '^BST skip ')
  pass=$((pass + _p)); fail=$((fail + _f)); skip=$((skip + _s))
}

echo "==BST-BEGIN=="
if [ $# -eq 0 ]; then
  for f in "$BST_TESTS"/*.test; do
    [ -e "$f" ] || continue
    run_one "$f"
  done
else
  for pat in "$@"; do
    for f in "$BST_TESTS"/*"$pat"*.test; do
      [ -e "$f" ] || continue
      run_one "$f"
    done
  done
fi
echo "==BST-SUMMARY pass=$pass fail=$fail skip=$skip total=$((pass + fail + skip))=="
echo "==BST-END=="

[ "$fail" -eq 0 ]
