#!/bin/bash
#------------------------------------------------------------------------------
# check.sh - The quick and the full check of the RVM
#
#   check.sh quick [-p PREFIX[,PREFIX...]] [-t PATTERN]
#   check.sh full  [-t PATTERN]
#
# quick (after any change; about 7-10 minutes on 2 cores), in parallel:
#   - the smoke test (../smoke/smoke.rex, both RVMs);
#   - the end-to-end tests of Classic Rexx on both RVMs (e2e/e2e.sh rvm, js);
#   - the external routine tests on both RVMs (ext/ext.sh rvm, js);
#   - the cache tests (cache/cache-test.sh);
#   - with -p, oo-e2e for each of the PREFIXes (cases whose name contains
#     it: -p rexxutil-,ctx-,conc-);
#   - with -t, the ooTest census of the groups whose path matches PATTERN
#     (after the rest; a basic grep regular expression, e.g. -t 'bif/TRUNC\.').
# full (when closing a batch of changes; about 40 minutes of wall time on a
# machine with enough cores), in parallel:
#   - everything in quick (-t: only that part of the census, as in quick);
#   - the full oo-e2e (oo/oo-e2e.sh, about 25 minutes on 2 cores);
#   - the whole ooTest census on the RVM of JavaScript (ootest/census.sh,
#     about 19 minutes), compared with the reference census
#     (ootest/census-js.tsv) by ootest/compare.py;
#   - the fuzzers of Classic Rexx on both oracles, with fixed seeds, and the
#     interactive trace tests (debug/debug-run.sh, debug/fuzz-debug.py);
#   - the OO fuzzers with fixed seeds (fuzz/oo/).
#
# The census needs an export of the ooRexx test suite: RVM_OOTEST_DIR, or
# $RVM_TESTS_TMP/ootest-svn, made with "svn export" when it is missing and
# svn is installed (otherwise the census is skipped, and the summary says
# so). The rxapi daemon is stopped (pkill -x rxapi) before the oo-e2e runs
# and after a census.
#
# Each part writes its log to $RVM_TESTS_TMP/check/NAME.log (see env.sh for
# RVM_TESTS_TMP, RVM_DIR and RVM_BIN). The summary gives, for each part, OK
# or FAIL (its exit code), its seconds and its result lines. The exit code
# is the number of parts that failed.
#
# This file is part of the RVM, the Rexx Virtual Machine
# [See https://rexx.epbcn.com/rexx-parser/]
#
# Copyright (c) 2026 Josep Maria Blasco <josep.maria.blasco@epbcn.com>
#
# License: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
#------------------------------------------------------------------------------
. "$(cd "$(dirname "$0")" && pwd)/env.sh"
usage() { sed -n '5,6p' "$0" | sed 's/^# *//' >&2; exit 255; }
MODE="$1"; shift
case "$MODE" in quick|full) ;; *) usage ;; esac
PREFIXES=""; PATTERN=""
while getopts "p:t:" o; do
  case "$o" in p) PREFIXES="${OPTARG//,/ }" ;; t) PATTERN="$OPTARG" ;; *) usage ;; esac
done
export RVM_CLOCK=${RVM_CLOCK:-virtual}
LOG="$RVM_TESTS_TMP/check"; rm -rf "$LOG"; mkdir -p "$LOG"
T0=$(date +%s)
NAMES=()

# job NAME COMMAND...: run COMMAND in the background, its output to the log.
job() {
  local name="$1"; shift
  NAMES+=("$name")
  ( s=$(date +%s); "$@" > "$LOG/$name.log" 2>&1; echo $? > "$LOG/$name.rc"
    echo $(( $(date +%s) - s )) > "$LOG/$name.secs" ) &
}

# Classic fuzzers and interactive trace on one oracle directory.
classic_fuzz() {
  local o="$1" bad=0 F="$RVM_TESTS/fuzz"
  bash "$F/fuzz-trace-run.sh"  "$o" 21 22 || bad=$((bad+1))
  bash "$F/fuzz-signal-run.sh" "$o" 21    || bad=$((bad+1))
  bash "$F/fuzz-call-run.sh"   "$o" 21 22 || bad=$((bad+1))
  bash "$F/fuzz-parse-run.sh"  "$o" 21    || bad=$((bad+1))
  bash "$F/fuzz-expose-run.sh" "$o" 21    || bad=$((bad+1))
  bash "$F/fuzz-whole-run.sh"  "$o" 21    || bad=$((bad+1))
  bash "$F/fuzz-strbif-run.sh" "$o" 21    || bad=$((bad+1))
  bash "$RVM_TESTS/debug/debug-run.sh" "$o" || bad=$((bad+1))
  python3 "$RVM_TESTS/debug/fuzz-debug.py" "$o" 100 21 "$RVM_TESTS_TMP/fuzz-debug-$(basename "$o")" || bad=$((bad+1))
  return $bad
}

# The OO fuzzers, two seeds each.
oo_fuzz() {
  local bad=0 F="$RVM_TESTS/fuzz/oo" s
  for s in 4 5; do
    bash "$F/fuzz-array-run.sh"   $s 100 || bad=$((bad+1))
    bash "$F/fuzz-strmeth-run.sh" $s 2   || bad=$((bad+1))
    bash "$F/fuzz-list-run.sh"    $s 60  || bad=$((bad+1))
    bash "$F/fuzz-hash-run.sh"    $s 40  || bad=$((bad+1))
    bash "$F/fuzz-stem-run.sh"    $s 40  || bad=$((bad+1))
    bash "$F/fuzz-mbuf-run.sh"    $s 2   || bad=$((bad+1))
  done
  return $bad
}

# The census (all of it, or the groups matching $1), compared with the
# reference census when it is the whole suite.
census() {
  local out="$RVM_TESTS_TMP/census" svn="${RVM_OOTEST_DIR:-$RVM_TESTS_TMP/ootest-svn}"
  if [ ! -f "$svn/ooTest.frm" ]; then
    if command -v svn >/dev/null; then
      echo "exporting the ooRexx test suite into $svn"
      svn export -q --force https://svn.code.sf.net/p/oorexx/code-0/test/trunk "$svn" || return 1
    else
      echo "census: SKIPPED (no ooTest export in $svn and no svn client)"; return 0
    fi
  fi
  rm -rf "$out"
  bash "$RVM_TESTS/ootest/census.sh" "$svn" "$out" "$1" 2
  local st=$?
  pkill -x rxapi
  awk -F'\t' '{n[$4]++} END {s=""; for (k in n) s=s" "n[k]" "k; print "census:" s}' "$out/census.tsv"
  if [ -z "$1" ]; then
    python3 "$RVM_TESTS/ootest/compare.py" "$RVM_TESTS/ootest/census-js.tsv" "$out/census.tsv" "$out/accepted.tsv"
  else
    # Without a reference: a group passes when SAME, or when every test the
    # native passes and the RVM does not is an accepted divergence.
    python3 - "$out" <<'EOF'
import sys, os
out = sys.argv[1]
acc = {}
p = os.path.join(out, "accepted.tsv")
if os.path.exists(p):
    for l in open(p): g, n = l.rstrip("\n").split("\t"); acc[g] = int(n)
def passed(c):
    c = c.split()
    return int(c[0]) - int(c[2]) - int(c[3]) if len(c) == 4 else 0
bad = 0
for l in open(os.path.join(out, "census.tsv"), encoding="latin-1"):
    g, n, e, st, secs = l.rstrip("\n").split("\t")
    if st in ("SAME", "SKIP", "NATIVE-FAIL"): continue
    if st == "DIFF" and passed(e) + acc.get(g, 0) >= passed(n):
        print(f"census group {g}: DIFF, all accepted ({acc.get(g, 0)})"); continue
    bad += 1; print(f"census group {g}: {st} (native {n}, rvm {e}) NOT ACCEPTED")
print(f"census groups not accepted: {bad}")
sys.exit(min(bad, 255))
EOF
    st=$?
  fi
  return $st
}

# The oracles are built once, before the fuzzers start.
if [ "$MODE" = full ]; then
  OR=$(rvm_oracle rvm); OJ=$(rvm_oracle js)
fi
if [ -n "$PREFIXES" ] || [ "$MODE" = full ]; then pkill -x rxapi; fi

job smoke     rexx "$RVM_DIR/smoke/smoke.rex" both
job e2e-rvm   bash "$RVM_TESTS/e2e/e2e.sh" rvm
job e2e-js    bash "$RVM_TESTS/e2e/e2e.sh" js
job ext-rvm   bash "$RVM_TESTS/ext/ext.sh" rvm
job ext-js    bash "$RVM_TESTS/ext/ext.sh" js
job cache     bash "$RVM_TESTS/cache/cache-test.sh"
if [ "$MODE" = quick ]; then
  for p in $PREFIXES; do
    job "oo-$p" env RVM_TESTS_OUT="$RVM_TESTS_TMP/oo-$p" bash "$RVM_TESTS/oo/oo-e2e.sh" "$p"
  done
else
  job oo-e2e     env RVM_TBCHECK=1 bash "$RVM_TESTS/oo/oo-e2e.sh"
  job census     census "$PATTERN"
  job fuzz-rvm   classic_fuzz "$OR"
  job fuzz-js    classic_fuzz "$OJ"
  job fuzz-oo    oo_fuzz
fi
wait
# In quick, the census of PATTERN runs last (alone: the daemon it leaves
# registrations in must not disturb the other parts).
if [ "$MODE" = quick ] && [ -n "$PATTERN" ]; then
  job census census "$PATTERN"; wait
fi

RESULT='^(smoke:|e2e \(|ext \(|cache:|oo-e2e|[A-Za-z -]+ fuzzer:|fuzz-debug:|debug:|census|accepted:|base:|new:|new \+ accepted:)'
fails=0
echo "check $MODE: ${#NAMES[@]} parts, $(( $(date +%s) - T0 )) s (logs in $LOG)"
for n in "${NAMES[@]}"; do
  rc=$(cat "$LOG/$n.rc" 2>/dev/null || echo 255); secs=$(cat "$LOG/$n.secs" 2>/dev/null || echo "?")
  if [ "$rc" = 0 ]; then st=OK; else st=FAIL; fails=$((fails+1)); fi
  printf "%-4s %-16s %5s s\n" "$st" "$n" "$secs"
  grep -aE "$RESULT" "$LOG/$n.log" | sed 's/^/       /'
done
exit "$fails"
