#!/bin/sh
# tests/run.sh - offline checks for plugin_sqlite across all 3 modes.
#
# Builds a throwaway SQLite database in a temp directory, points the plugin at
# it with SQLITE_ALLOWED_ROOT, and proves:
#   * discovery, schema and query all answer with well-formed JSON
#   * the read-only contract holds (INSERT/UPDATE/DELETE/DROP/ALTER/ATTACH/
#     CREATE are refused, both by the statement guard and by the authorizer)
#   * path traversal, system paths and SQLite URI filenames are refused
#   * the row cap and the statement time budget actually bite
#   * node auth (401 / X-Bot-Password / Bearer / ?pwd=) behaves
#   * the musl static build and the Windows PE are the right kind of file
#   * the whole git history carries no secret and no LAN IP
#
# If musl / arm64 / Win64 artifacts are present they are checked too.
# Exit code 0 = everything passed.

set -u

ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$ROOT" || exit 1

BIN=./plugin_sqlite
PASS=0
FAIL=0

if [ -t 1 ]; then
    C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
else
    C_OK=; C_BAD=; C_B=; C_0=
fi
pass() { PASS=$((PASS + 1)); printf '  %sok%s   %s\n' "$C_OK" "$C_0" "$1"; }
fail() { FAIL=$((FAIL + 1)); printf '  %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }

check() { # check <desc> <expected-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
        fail "$1 (want: $2)"; printf '       got: %s\n' "$(printf '%s' "$3" | head -c 300)"
    fi
}

check_not() { # check_not <desc> <forbidden-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then
        fail "$1 (must NOT contain: $2)"; else pass "$1"
    fi
}

section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }

# Strip the CGI header block, leaving the body.
body() { printf '%s' "$1" | sed '1,/^\r$/d'; }

[ -x "$BIN" ] || { printf '%smissing %s - run make first%s\n' "$C_BAD" "$BIN" "$C_0" >&2; exit 1; }

TMP=$(mktemp -d 2>/dev/null || echo "/tmp/plugin_sqlite_test.$$")
mkdir -p "$TMP"
trap 'rm -rf "$TMP"' EXIT 2>/dev/null || true

# Export so every invocation below sees a narrow, predictable allowlist.
SQLITE_ALLOWED_ROOT="$TMP"; export SQLITE_ALLOWED_ROOT

# ---------------------------------------------------------------- fixture
section "fixture"
if ! command -v python3 >/dev/null 2>&1; then
    printf '%sFAIL%s python3 is required to build the test database\n' "$C_BAD" "$C_0" >&2
    exit 1
fi

python3 - "$TMP" <<'PY' || exit 1
import sqlite3, sys, os
tmp = sys.argv[1]
db = os.path.join(tmp, "shop.sqlite")
if os.path.exists(db):
    os.remove(db)
c = sqlite3.connect(db)
c.executescript("""
CREATE TABLE customers(id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT);
CREATE TABLE orders(id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id),
                    total REAL, note BLOB, created TEXT);
CREATE INDEX idx_orders_cust ON orders(customer_id);
CREATE VIEW big_orders AS SELECT * FROM orders WHERE total > 100;
INSERT INTO customers(name,email) VALUES ('Ada','ada@example.com'),('Bo',NULL);
""")
for i in range(1200):
    c.execute("INSERT INTO orders(customer_id,total,note,created) VALUES(?,?,?,?)",
              (1 + (i % 2), (i % 500) + 0.5, b"\x01\x02", "2026-03-%02d" % (i % 28 + 1)))
c.commit()
c.close()
open(os.path.join(tmp, "notes.txt"), "w").write("not a database\n")
open(os.path.join(tmp, "fake.db"), "w").write("this is definitely not sqlite\n")
print("  fixture: %s (%d bytes)" % (db, os.path.getsize(db)))
PY
[ -f "$TMP/shop.sqlite" ] && pass "test database created" || { fail "test database missing"; exit 1; }

DB="$TMP/shop.sqlite"

# ---------------------------------------------------------------- mode 1
section "mode 1 --meta"
META=$("$BIN" --meta)
check      "meta emits name sqlite"        '"name":"sqlite"'          "$META"
check      "meta emits desc SQLite viewer" '"desc":"SQLite viewer"'   "$META"
METAENV=$(SX_PLUGIN_META=1 "$BIN")
check      "SX_PLUGIN_META=1 yields same meta" '"name":"sqlite"'      "$METAENV"
LEN=$(printf '%s' "$META" | wc -c | tr -d ' ')
[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)"
printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
    && pass "meta is valid JSON" || fail "meta is not valid JSON"
DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/')
[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})"
NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/')
[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces"
check      "--version prints version"      '1.0.3'                    "$("$BIN" --version)"

# ------------------------------------------------- CGI framing (Windows trap)
# MinGW/MSVC CRT stdout defaults to TEXT mode, rewriting every \n into \r\n.
# A CGI header block must end with exactly CRLF CRLF; text mode yields
# CR CR LF CR CR LF, scorpiox-server cannot find the header/body separator and
# the reply comes back mangled. Live-confirmed on a Windows NTFS node
# (2026-11-12) with the shipped 1.0.2 windows-x86_64 artifact.
section "CGI header framing (no CR CR LF)"
FRAMETMP=$(mktemp)
cgi_hex() { od -An -tx1 "$1" | tr -s ' \t\n' ' '; }
cgi_frame_check() { # cgi_frame_check <desc> <query>
    BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="$2" "$BIN" > "$FRAMETMP"
    H=$(cgi_hex "$FRAMETMP")
    case " $H " in *" 0d 0d 0a "*) fail "$1: found CR CR LF (text-mode stdout)"; return;; esac
    case " $H " in *" 0d 0a 0d 0a "*) pass "$1: exact CRLF CRLF header separator";;
        *) fail "$1: no CRLF CRLF separator found";;
    esac
}
cgi_frame_check "html mode framing"   ""
cgi_frame_check "dbs action framing"  "action=dbs"
cgi_frame_check "info action framing" "action=info"
rm -f "$FRAMETMP"
check      "--version names the sqlite lib" 'sqlite 3.'               "$("$BIN" --version)"
check      "--help is available"           'usage:'                   "$("$BIN" --help)"
META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta)
check      "meta still works when BOT_PASSWORD is set" '"name":"sqlite"' "$META_AUTH"

# ---------------------------------------------------------------- auth
section "node auth"
AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=info' "$BIN")
check      "no credentials -> 401"          'Status: 401'            "$AUTHNONE"
check      "401 body is json"               'invalid node password'  "$AUTHNONE"
AUTHH=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=info' "$BIN")
check      "X-Bot-Password accepted"        '"ok":true'              "$(body "$AUTHH")"
AUTHB=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=info' "$BIN")
check      "Bearer token accepted"          '"ok":true'              "$(body "$AUTHB")"
AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=info&pwd=testpw' "$BIN")
check      "?pwd= accepted"                 '"ok":true'              "$(body "$AUTHQ")"
AUTHBAD=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=info' "$BIN")
check      "wrong password -> 401"          'Status: 401'            "$AUTHBAD"
HTMLAUTH=$(BOT_PASSWORD=testpw QUERY_STRING='' "$BIN")
check      "html mode is also gated"        'Status: 401'            "$HTMLAUTH"

# ---------------------------------------------------------------- dbs
section "mode 2 action=dbs"
DBS=$(body "$(QUERY_STRING='action=dbs' "$BIN")")
printf '%s' "$DBS" > "$TMP/dbs.json"
check      "dbs ok:true"                    '"ok":true'              "$DBS"
check      "dbs names the plugin"           '"plugin":"plugin_sqlite"' "$DBS"
check      "dbs declares read-only"         '"readonly":true'        "$DBS"
check      "dbs carries the allowed root"   "$TMP"                   "$DBS"
check      "dbs finds our database"         'shop.sqlite'            "$DBS"
check      "dbs reports a count"            '"count":'               "$DBS"
check      "dbs reports per-root fields"    '"scanned_entries":'     "$DBS"
check      "dbs declares the scan cap"      '"max_scan_entries":'    "$DBS"
printf '%s' "$DBS" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
    && pass "dbs body is valid JSON" || fail "dbs body JSON invalid"
python3 - "$TMP/dbs.json" <<'PYEOF' && pass "dbs rows are well formed" || fail "dbs rows malformed"
import json, sys
d = json.load(open(sys.argv[1]))
assert d["ok"] is True
assert d["count"] == len(d["dbs"])
assert d["count"] >= 1
names = [x["path"] for x in d["dbs"]]
assert any(p.endswith("shop.sqlite") for p in names), names
assert not any(p.endswith("notes.txt") for p in names), names
for x in d["dbs"]:
    assert x["bytes"] > 0
    assert x["root"]
    assert x["mtime"].endswith("Z")
for r in d["roots"]:
    for k in ("label", "path", "exists", "dbs", "scanned_entries", "truncated"):
        assert k in r, (k, r)
    assert isinstance(r["dbs"], int) and r["dbs"] >= 0
    assert isinstance(r["scanned_entries"], int) and r["scanned_entries"] >= 0
    assert isinstance(r["truncated"], bool)
assert d["max_scan_entries"] > 0
PYEOF
check_not "dbs ignores non-db files"        'notes.txt'              "$DBS"

# Every allowlisted root must get its own scan budget. One global counter let a
# large tree exhaust the allowance before the walk reached $HOME, so a database
# in the home directory was simply invisible. SQLITE_SCAN_BUDGET shrinks the
# allowance so a five-directory fixture can prove it.
BIGDIR="$TMP/bigtree"
mkdir -p "$BIGDIR"
for i in 1 2 3 4 5 6 7 8 9; do mkdir -p "$BIGDIR/f$i"; done
ROOTRUN=$(SQLITE_ALLOWED_ROOT="$BIGDIR" SQLITE_SCAN_BUDGET=4 QUERY_STRING='action=dbs' "$BIN" | sed '1,/^\r$/d')
check      "dbs reports per-root scan counts" '"scanned_entries":'  "$ROOTRUN"
check      "dbs flags the truncated root"     '"truncated":true'    "$ROOTRUN"
HOMEHIT=$(printf '%s' "$ROOTRUN" | python3 -c '
import json, sys
d = json.load(sys.stdin)
labels = {r["label"]: r for r in d["roots"]}
assert labels["allowed"]["truncated"] is True, labels["allowed"]
home = labels.get("home")
assert home is not None, labels
if home["exists"]:
    assert home["scanned_entries"] > 0 or home["dbs"] > 0, home
    print("home_walked", home["scanned_entries"])
' 2>/dev/null)
case "$HOMEHIT" in
home_walked*) pass "home is still walked after a truncated root" ;;
*) fail "home was skipped after a truncated root (got: $HOMEHIT)" ;;
esac

# ---------------------------------------------------------------- schema
section "mode 2 action=schema"
SCHEMA=$(body "$(QUERY_STRING="action=schema&db=$DB" "$BIN")")
printf '%s' "$SCHEMA" > "$TMP/schema.json"
check      "schema ok:true"                 '"ok":true'              "$SCHEMA"
check      "schema names the database"      "$DB"                    "$SCHEMA"
check      "schema lists customers"         '"name":"customers"'     "$SCHEMA"
check      "schema lists orders"            '"name":"orders"'        "$SCHEMA"
check      "schema marks the view"          '"type":"view"'          "$SCHEMA"
check      "schema reports the index"       'idx_orders_cust'        "$SCHEMA"
check      "schema has column detail"       '"notnull":true'         "$SCHEMA"
python3 - "$TMP/schema.json" <<'PYEOF' && pass "schema rows are well formed" || fail "schema malformed"
import json, sys
d = json.load(open(sys.argv[1]))
assert d["ok"] is True and d["readonly"] is True
tables = {t["name"]: t for t in d["tables"]}
assert "customers" in tables and "orders" in tables and "big_orders" in tables
assert tables["orders"]["rows"] == 1200, tables["orders"]["rows"]
assert tables["customers"]["rows"] == 2
cols = {c["name"]: c for c in tables["orders"]["columns"]}
assert cols["customer_id"]["type"] == "INTEGER"
assert [i["name"] for i in tables["orders"]["indexes"]] == ["idx_orders_cust"]
assert tables["customers"]["type"] == "table"
assert tables["big_orders"]["type"] == "view"
PYEOF
SCHEMA_MISS=$(body "$(QUERY_STRING="action=schema&db=$TMP/nope.sqlite" "$BIN")")
SCHEMA_FAKE=$(body "$(QUERY_STRING="action=schema&db=$TMP/fake.db" "$BIN")")
check      "non-sqlite file -> not_a_database" 'not_a_database'      "$SCHEMA_FAKE"

# ---------------------------------------------------------------- query
section "mode 2 action=query (allowed)"
Q1=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+count(*)+from+orders" "$BIN")")
check      "count(*) works"                 '[[1200]]'               "$Q1"
check      "query reports row_count"        '"row_count":1'          "$Q1"
check      "query reports elapsed ms"       '"ms":'                  "$Q1"
check      "query reports column types"     '"types":["int"]'        "$Q1"

Q2=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+name,email+from+customers+order+by+id" "$BIN")")
check      "text values are quoted"         '"Ada"'                  "$Q2"
check      "NULL becomes json null"         'null'                   "$Q2"

Q3=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+total,note+from+orders+limit+1" "$BIN")")
check      "real numbers are emitted"       '"total"'                "$Q3"
check      "blobs become a hex preview"     '"blob_bytes":2'         "$Q3"
check      "blob hex is the real bytes"     '"hex":"0102"'           "$Q3"

Q4=$(body "$(QUERY_STRING="action=query&db=$DB&sql=pragma+table_info(orders)" "$BIN")")
check      "read-only pragma runs"          '"customer_id"'         "$Q4"

Q5=$(body "$(QUERY_STRING="action=query&db=$DB&sql=pragma+integrity_check" "$BIN")")
check      "integrity_check runs"           '"ok"'                   "$Q5"

Q6=$(body "$(QUERY_STRING="action=query&db=$DB&sql=WITH+o+AS+(SELECT+id+FROM+orders)+SELECT+count(*)+FROM+o" "$BIN")")
check      "WITH / CTE select works"        '[[1200]]'               "$Q6"

Q7=$(body "$(QUERY_STRING="action=query&db=$DB&sql=explain+select+1" "$BIN")")
check      "EXPLAIN works"                  '"ok":true'              "$Q7"

# POST-style body parsing
printf 'sql=select+42+as+answer' > "$TMP/body.txt"
Q8=$(body "$(HTTP_BODY_FILE="$TMP/body.txt" QUERY_STRING="action=query&db=$DB" "$BIN")")
check      "POST body sql= is parsed"       '[[42]]'                 "$Q8"

# ---------------------------------------------------------------- row cap
section "row cap and time budget"
CAP=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+*+from+orders" "$BIN")")
check      "unbounded select is capped"     '"row_count":500'        "$CAP"
check      "cap is flagged as truncated"    '"truncated":true'       "$CAP"
check      "cap declares the limit"         '"limit":500'            "$CAP"
printf '%s' "$CAP" | python3 -c '
import json,sys
d = json.load(sys.stdin)
assert len(d["rows"]) == 500, len(d["rows"])
assert d["row_count"] == 500
' 2>/dev/null && pass "exactly 500 rows were streamed" || fail "row cap did not produce 500 rows"

BUDGET=$(body "$(QUERY_STRING="action=query&db=$DB&sql=WITH+RECURSIVE+c(i)+AS(SELECT+1+UNION+ALL+SELECT+i%2B1+FROM+c+WHERE+i%3C30000000)+SELECT+count(*)+FROM+c" "$BIN")")
check      "runaway recursion is stopped"   '"aborted":true'        "$BUDGET"

# ---------------------------------------------------------------- read-only
section "read-only enforcement"
deny() { # deny <desc> <sql>
    local out
    out=$(body "$(QUERY_STRING="action=query&db=$DB&sql=$2" "$BIN")")
    case "$out" in
    *'"ok":false'*) pass "$1 rejected" ;;
    *) fail "$1 was NOT rejected: $(printf '%s' "$out" | head -c 200)" ;;
    esac
}
deny "INSERT"          "insert+into+customers(name)+values('x')"
deny "UPDATE"          "update+customers+set+name='x'"
deny "DELETE"          "delete+from+customers"
deny "DROP TABLE"      "drop+table+orders"
deny "ALTER TABLE"     "alter+table+orders+add+column+x+int"
deny "CREATE TABLE"    "create+table+x(a)"
deny "CREATE VIEW"     "create+view+v+as+select+1"
deny "ATTACH"          "attach+%27$TMP%2Fevil.db%27+as+evil"
deny "DETACH"          "detach+main"
deny "REINDEX"         "reindex"
deny "VACUUM"          "vacuum"
deny "BEGIN"           "begin"
deny "PRAGMA write"    "pragma+user_version%3D5"
deny "stacked stmt"    "select+1%3B+drop+table+orders"
deny "WITH-DELETE"     "WITH+x+AS(SELECT+1)+DELETE+FROM+customers"

# Row-count evidence that nothing above actually mutated the file.
AFTER=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+count(*)+from+orders" "$BIN")")
check      "orders still has 1200 rows"     '[[1200]]'               "$AFTER"
AFTER_C=$(body "$(QUERY_STRING="action=query&db=$DB&sql=select+count(*)+from+customers" "$BIN")")
check      "customers still has 2 rows"     '[[2]]'                  "$AFTER_C"
[ ! -f "$TMP/evil.db" ] && pass "ATTACH created no file" || fail "ATTACH created $TMP/evil.db"

# The authorizer is the second line of defence; prove it fires directly.
python3 - "$DB" <<'PY' && pass "on-disk mtime proves no write happened" || fail "database file changed"
import os, sqlite3, sys, time
db = sys.argv[1]
before = os.stat(db).st_mtime
c = sqlite3.connect(db)
c.execute("SELECT count(*) FROM orders").fetchone()
c.close()
assert os.stat(db).st_mtime == before
PY

# ---------------------------------------------------------------- paths
section "path discipline"
bad_path() { # bad_path <desc> <db-query-value>
    local out
    out=$(body "$(QUERY_STRING="action=query&db=$2&sql=select+1" "$BIN")")
    case "$out" in
    *forbidden_path*) pass "$1 rejected" ;;
    *) fail "$1 was NOT rejected: $(printf '%s' "$out" | head -c 200)" ;;
    esac
}
bad_path "/etc/passwd"                 "/etc/passwd"
bad_path "../ traversal"               "$TMP/../../etc/passwd"
bad_path "encoded traversal"           "$TMP/%2e%2e/%2e%2e/etc/passwd"
bad_path "SQLite URI filename"         "file:$DB"
bad_path "URI with mode=rwc"           "file:$DB%3Fmode%3Drwc"
bad_path "http scheme"                 "http://example.com/x.db"
bad_path "non-db suffix"               "$TMP/notes.txt"
bad_path "arbitrary root"              "/etc/hosts.db"

MISSING=$(body "$(QUERY_STRING="action=query&db=$TMP/absent.sqlite&sql=select+1" "$BIN")")
check      "allowed location, missing file -> not_found" 'not_found'  "$MISSING"

# ---------------------------------------------------------------- misc
section "mode 2 misc"
INFO=$(body "$(QUERY_STRING='action=info' "$BIN")")
check      "info names the plugin"          '"plugin":"plugin_sqlite"' "$INFO"
check      "info names the sqlite version"  '"sqlite":"3.'           "$INFO"
check      "info declares read-only"        '"readonly":true'        "$INFO"
check      "info declares zero_network"     '"zero_network":true'    "$INFO"
check      "info declares no extension load" '"load_extension":false' "$INFO"
check      "info lists the actions"         '"dbs","schema","query","info"' "$INFO"
check      "info declares max_rows"         '"max_rows":500'         "$INFO"

UNK=$(body "$(QUERY_STRING='action=nope' "$BIN")")
check      "unknown action is refused"      'unknown_action'         "$UNK"
JSONF=$(body "$(QUERY_STRING='format=json' "$BIN")")
check      "format=json falls back to dbs"  '"action":"dbs"'         "$JSONF"
NOSQL=$(body "$(QUERY_STRING="action=query&db=$DB" "$BIN")")
check      "query without sql -> missing_sql" 'missing_sql'          "$NOSQL"

# ---------------------------------------------------------------- mode 3
section "mode 3 html"
HTML=$("$BIN")
check      "html content type"              'Content-Type: text/html' "$HTML"
check      "html has a doctype"             '<!DOCTYPE html>'        "$HTML"
check      "html titles the tool"           '<title>sqlite</title>'  "$HTML"
check      "html ships the sql editor"      "id='sql'"              "$HTML"
check      "html ships the db picker"       "id='dbsel'"            "$HTML"
check      "html shows which roots were walked" "id='rootline'"      "$HTML"
check      "html ships the result grid"     "id='reswrap'"          "$HTML"
check      "html supports ctrl+enter"       'Ctrl'                  "$HTML"
check      "html offers CSV copy"           'Copy CSV'              "$HTML"
check      "html offers JSON copy"          'Copy JSON'             "$HTML"
check      "html declares the node route"   '/plugin_sqlite?action=' "$HTML"
check      "html declares the hub route"    "/plugins?plugin="      "$HTML"
check      "html honours embed"             "/plugin_sqlite?action=" "$HTML"
check      "html supports light theme"      "data-theme=light"      "$HTML"

# ---- theme handoff (bot_theme_plugin.h) ----
# the bot owns the theme: ?theme= before first paint, sx-theme after it
check      "html reads ?theme= before paint"  'theme=(light|dark)'          "$HTML"
check      "html listens for sx-theme"         "d.type==='sx-theme'"        "$HTML"
check      "html asks the host for the theme"  "sx-theme-request"           "$HTML"
check      "html uses bot token --bg-card"     "--bg-card"                  "$HTML"
check      "html uses bot token --surface-2"   "--surface-2"                "$HTML"
check      "html uses bot token --text-2"      "--text-2"                   "$HTML"
check      "html hides its toggle when embedded" "embed-hide"               "$HTML"
check_not  "html no retired brand casing" 'Scorpio'"X Bot"           "$HTML"
check_not  "html no private palette 0b0b0e"     '0b0b0e'                       "$HTML"
check_not  "html no private palette 141419"     '141419'                       "$HTML"
check_not  "html no private palette f2f2f6"     'f2f2f6'                       "$HTML"
THEMEQ=$(QUERY_STRING='theme=light' "$BIN")
check      "?theme=light still renders the UI"  'prefers-color-scheme'     "$THEMEQ"
# ---- end theme handoff ----

check_not  "html has no CDN script"         '<script src='          "$HTML"
check_not  "html has no cdnjs"              'cdnjs'                 "$HTML"
check_not  "html emits no Content-Length"   'Content-Length'        "$HTML"
EMBED=$("$BIN" </dev/null 2>/dev/null | head -1)
EMBEDQ=$(QUERY_STRING='embed=1' "$BIN")
check_not  "embed=1 drops the back link"    'Back to Bot'           "$EMBEDQ"
check      "non-embed keeps the back link"  'Back to Bot'           "$HTML"

# ---------------------------------------------------------------- artifacts
section "cross builds"
if [ -f plugin_sqlite.musl ]; then
    MAGIC=$(od -An -tx1 -N4 plugin_sqlite.musl | tr -d ' \n')
    [ "$MAGIC" = "7f454c46" ] && pass "musl artifact is an ELF" || fail "musl artifact is not ELF ($MAGIC)"
    python3 - plugin_sqlite.musl <<'PY' && pass "musl artifact is x86_64 (EM_X86_64=62)" || fail "musl artifact wrong machine"
import sys, struct
d = open(sys.argv[1], "rb").read(20)
assert d[4] == 2, "not 64-bit"
assert d[5] == 1, "not little-endian"
assert struct.unpack("<H", d[18:20])[0] == 62
PY
    if command -v readelf >/dev/null 2>&1; then
        readelf -d plugin_sqlite.musl 2>/dev/null | grep -q NEEDED \
            && fail "musl artifact is dynamically linked" || pass "musl artifact is fully static"
    fi
else
    printf '  skip musl artifact (not built)\n'
fi

if [ -f plugin_sqlite.arm64 ]; then
    python3 - plugin_sqlite.arm64 <<'PY' && pass "arm64 artifact is EM_AARCH64 (183)" || fail "arm64 artifact wrong machine"
import sys, struct
d = open(sys.argv[1], "rb").read(20)
assert d[4] == 2, "not 64-bit"
assert d[5] == 1, "not little-endian"
assert struct.unpack("<H", d[18:20])[0] == 183
PY
else
    printf '  skip arm64 artifact (not built)\n'
fi

if [ -f plugin_sqlite.exe ]; then
    MZ=$(head -c 2 plugin_sqlite.exe)
    [ "$MZ" = "MZ" ] && pass "windows artifact starts with MZ" || fail "windows artifact is not a PE"
    SZ=$(wc -c < plugin_sqlite.exe | tr -d ' ')
    [ "$SZ" -gt 200000 ] && pass "windows artifact is not an error page ($SZ bytes)" || fail "windows artifact suspiciously small ($SZ bytes)"
else
    printf '  skip windows artifact (not built)\n'
fi

# ---------------------------------------------------------------- history
section "git history audit"
if [ -d .git ]; then
    SCAN="$TMP/history.txt"
    P_ROOT=$(pwd); P_WT=$(pwd)
    git log -p --all 2>/dev/null \
      | grep -v '^Author: ' \
      | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \
      > "$SCAN" || : > "$SCAN"
    HITS=0
    scan() { # scan <label> <regex>
        out=$(grep -Eo "$2" "$SCAN" 2>/dev/null | sort -u | head -5 || true)
        if [ -n "$out" ]; then
            printf '  %sHIT%s  %s\n         %s\n' "$C_BAD" "$C_0" "$1" "$(printf '%s' "$out" | tr '\n' ' ')"
            HITS=$((HITS + 1))
        else
            pass "no $1 in history"
        fi
    }
    scan "LAN IPs 192.168.x.x"        '192\.168\.[0-9]+\.[0-9]+'
    scan "private 10.x.x.x"           '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
    scan "private 172.16-31.x.x"      '\b172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
    scan "GitHub tokens"              'ghp_[A-Za-z0-9]{20,}'
    scan "HuggingFace tokens"         'hf_[A-Za-z0-9]{20,}'
    scan "AWS access keys"            'AKIA[0-9A-Z]{16}'
    scan "OpenAI keys"                'sk-[A-Za-z0-9]{32,}'
    scan "private keys"               'BEGIN (RSA|OPENSSH|EC|PGP) PRIVATE KEY'
    scan "passwords in source"        '(password|passwd|secret)[[:space:]]*=[[:space:]]*"[^"]{4,}"'
    [ "$HITS" -eq 0 ] && pass "history audit clean (0 hits)" || fail "history audit found $HITS category(ies)"
else
    printf '  skip history audit (not a git repo)\n'
fi

# ---------------------------------------------------------------- summary
printf '\n%s----------------------------------------%s\n' "$C_B" "$C_0"
printf '  %spass %d%s   %sfail %d%s\n' "$C_OK" "$PASS" "$C_0" "$([ "$FAIL" -eq 0 ] && printf '%s' "$C_OK" || printf '%s' "$C_BAD")" "$FAIL" "$C_0"
[ "$FAIL" -eq 0 ] && { printf '  %sALL PASS%s\n' "$C_OK" "$C_0"; exit 0; }
printf '  %sFAILURES%s\n' "$C_BAD" "$C_0"
exit 1
