#!/bin/sh
# tests/run.sh - offline checks for plugin_sysmon across all 3 modes.
#
# Runs against ./plugin_sysmon (native build) on the live machine, so the
# metrics assertions use this node's real /proc (or mach / Win32) counters.
# If a musl static build or a Windows PE (plugin_sysmon.exe) is present they are
# checked too. The whole git history is finally audited for secrets and LAN IPs.
#
# Exit code 0 = everything passed.

set -u

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

BIN=./plugin_sysmon
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"; }

body() { printf '%s' "$1" | sed '1,/^\r$/d'; }

# ---------------------------------------------------------------- build
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    cc -O2 -std=c99 -Wall -Wextra -o "$BIN" src/plugin_sysmon.c || { echo "  build failed"; exit 1; }
fi
[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"

# ---------------------------------------------------------------- meta mode
section "mode 1 --meta (must work without auth - discovery)"
META=$("$BIN" --meta)
check      "meta emits name sysmon"        '"name":"sysmon"'        "$META"
check      "meta emits desc CPU & memory"  '"desc":"CPU & memory"'  "$META"
METAENV=$(SX_PLUGIN_META=1 "$BIN")
check      "SX_PLUGIN_META=1 yields same meta" '"name":"sysmon"'    "$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.2'                 "$("$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":"sysmon"' "$META_AUTH"

# ---------------------------------------------------------------- auth
section "node auth"
AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=metrics' "$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=metrics' "$BIN")
check      "X-Bot-Password accepted"        '"ok":true'             "$(body "$AUTHH")"
AUTHB=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=metrics' "$BIN")
check      "Authorization Bearer accepted"  '"ok":true'             "$(body "$AUTHB")"
AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=metrics&pwd=testpw' "$BIN")
check      "?pwd= accepted (plugin iframe)" '"ok":true'             "$(body "$AUTHQ")"
AUTHBAD=$(BOT_PASSWORD=testpw QUERY_STRING='action=metrics&pwd=wrong' "$BIN")
check      "wrong ?pwd= rejected"           'Status: 401'           "$AUTHBAD"
AUTHHTML=$(BOT_PASSWORD=testpw QUERY_STRING='' "$BIN")
check      "html also requires auth"        'Status: 401'           "$AUTHHTML"

# ---------------------------------------------------------------- metrics
section "mode 2 action=metrics (live counters)"
RAW=$(QUERY_STRING='action=metrics' "$BIN")
MB=$(body "$RAW")
check_not  "metrics has no Content-Length"  'Content-Length'        "$RAW"
check      "metrics content-type json"      'Content-Type: application/json' "$RAW"
check      "metrics ok:true"                '"ok":true'             "$MB"
check      "metrics action echoed"          '"action":"metrics"'    "$MB"
check      "metrics has cpu_pct"            '"cpu_pct":'            "$MB"
check      "metrics has ncores"             '"ncores":'             "$MB"
check      "metrics has mem block"          '"mem":{"total_kb":'    "$MB"
check      "metrics has swap block"         '"swap":{"total_kb":'   "$MB"
check      "metrics has uptime"             '"uptime_sec":'         "$MB"
check      "metrics has load block"         '"load":{"available":'  "$MB"
check      "metrics has processes"          '"processes":['         "$MB"
check      "metrics has host"               '"host":'               "$MB"
check      "metrics has cpu_model"          '"cpu_model":'          "$MB"
check      "metrics has utc"                '"utc":"20'             "$MB"
check      "metrics top defaults to min(25, proc_count)" '"top":'        "$MB"
printf '%s' "$MB" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
    && pass "metrics body is valid JSON" || fail "metrics body JSON invalid"

# real, non-zero assertions - these are what prove the sampler works
MJ=/tmp/sysmon_metrics_$$.json
printf '%s' "$MB" > "$MJ"
python3 - "$MJ" <<'PY' && pass "live counters are non-zero and in range" || fail "live counters wrong"
import json,sys
d=json.load(open(sys.argv[1]))
assert d["mem"]["total_kb"] > 0, "mem_total must be > 0"
assert d["mem"]["used_kb"] > 0, "mem_used must be > 0"
assert 0 <= d["mem"]["pct"] <= 100
assert 0 <= d["cpu_pct"] <= 100
assert d["ncores"] >= 1
assert len(d["cores"]) == d["ncores"]
for c in d["cores"]:
    assert 0 <= c["pct"] <= 100
assert d["uptime_sec"] > 0, "uptime must be > 0"
assert d["proc_count"] > 0, "proc_count must be > 0"
assert len(d["processes"]) == d["top"]
assert d["top"] <= d["proc_count"]
assert d["swap"]["total_kb"] >= 0
PY

python3 - "$MJ" <<'PY' && pass "process rows carry pid, name, cpu, rss" || fail "process rows malformed"
import json,sys
d=json.load(open(sys.argv[1]))
assert len(d["processes"]) > 0
for p in d["processes"]:
    assert isinstance(p["pid"], int) and p["pid"] > 0
    assert isinstance(p["name"], str) and p["name"]
    assert p["cpu"] >= 0
    assert isinstance(p["rss_kb"], int) and p["rss_kb"] >= 0
PY

python3 - "$MJ" <<'PY' && pass "cpu percentages are sorted descending" || fail "cpu sort wrong"
import json,sys
d=json.load(open(sys.argv[1]))
vals=[p["cpu"] for p in d["processes"]]
assert vals == sorted(vals, reverse=True), vals
PY
rm -f "$MJ"

section "mode 2 sorting, limits and unknown actions"
MEMF=/tmp/sysmon_mem_$$.json
MEM=$(body "$(QUERY_STRING='action=metrics&sort=mem&top=5' "$BIN")")
printf '%s' "$MEM" > "$MEMF"
check      "sort=mem echoed"                '"sort":"mem"'          "$MEM"
check      "top=5 honoured"                 '"top":5'               "$MEM"
python3 - "$MEMF" <<'PY' && pass "memory sort is descending" || fail "mem sort wrong"
import json,sys
d=json.load(open(sys.argv[1]))
v=[p["rss_kb"] for p in d["processes"]]
assert v == sorted(v, reverse=True), v
assert len(v) <= 5
PY
rm -f "$MEMF"
TOP1=$(body "$(QUERY_STRING='action=metrics&top=1' "$BIN")")
check      "top=1 honoured"                 '"top":1'               "$TOP1"
UNK=$(QUERY_STRING='action=bogus' "$BIN")
check      "unknown action rejected"        'unknown_action'        "$(body "$UNK")"
check      "unknown action lists supported" '"supported":["metrics","info"]' "$(body "$UNK")"
check      "unknown action echoes request"  '"requested":"bogus"'   "$(body "$UNK")"
BIGTOP=$(body "$(QUERY_STRING='action=metrics&top=99999' "$BIN")")
check      "absurd top still returns a valid snapshot" '"ok":true'    "$BIGTOP"
check      "absurd top is capped" '"top":' "$BIGTOP"

section "mode 2 action=info"
INFO=$(QUERY_STRING='action=info' "$BIN")
IBODY=$(body "$INFO")
check      "info ok:true"                   '"ok":true'             "$IBODY"
check      "info action info"               '"action":"info"'       "$IBODY"
check      "info pid present"               '"pid":'                "$IBODY"
check      "info utc present"               '"utc":"20'             "$IBODY"
check      "info zero_network declared"     '"zero_network":true'   "$IBODY"
check      "info sample window declared"    '"samples_cpu_delta_ms":80' "$IBODY"
check      "info node_auth false when unset" '"node_auth":false'    "$IBODY"
INFOAUTH=$(body "$(BOT_PASSWORD=pw QUERY_STRING='action=info&pwd=pw' "$BIN")")
check      "info node_auth true when set"   '"node_auth":true'      "$INFOAUTH"
printf '%s' "$IBODY" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
    && pass "info body is valid JSON" || fail "info body JSON invalid"
check      "format=json works as alias"     '"action":"metrics"'    "$(body "$(QUERY_STRING='format=json&top=2' "$BIN")")"

# ---------------------------------------------------------------- html
section "mode 3 HTML"
HTML=$(QUERY_STRING='' "$BIN")
check      "html content-type"              'Content-Type: text/html; charset=utf-8' "$HTML"
check_not  "html has no Content-Length"     'Content-Length'        "$HTML"
check      "html has viewport meta"         'width=device-width'    "$HTML"
check      "html title sysmon"              '<title>sysmon</title>' "$HTML"
check      "html back-link present"         'Back to Bot'           "$HTML"
check      "html theme switch hook"         'bot_theme'             "$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      "html per-core host"             "id='cores'"            "$HTML"
check      "html history sparkline"         "id='spark'"            "$HTML"
check      "html memory gauge"              "memFill"               "$HTML"
check      "html swap gauge"                "swapFill"              "$HTML"
check      "html process table host"        "id='rows'"             "$HTML"
check      "html process filter input"      "id='q'"                "$HTML"
check      "html rate segmented control"    'data-ms='              "$HTML"
check      "html sort segmented control"    'data-sort='            "$HTML"
check      "html calls the metrics action"  'action=metrics'        "$HTML"
check      "html uses /plugins?plugin= route" "/plugins?plugin="    "$HTML"
check      "html falls back to /plugin_sysmon" "/plugin_sysmon"     "$HTML"
check      "html closes document"           '</html>'               "$HTML"
check      "html declares zero network"     'zero outbound network' "$HTML"
EMB=$(QUERY_STRING='embed=1' "$BIN")
check_not  "embed=1 strips the back-link"   'Back to Bot'           "$EMB"
check      "embed=1 still renders the UI"   "id='cores'"            "$EMB"
EMBT=$(QUERY_STRING='embed=true' "$BIN")
check_not  "embed=true also strips back-link" 'Back to Bot'         "$EMBT"

ZEROEMOJI=$(printf '%s' "$HTML" | python3 -c '
import sys
s = sys.stdin.read()
bad = [c for c in s if ord(c) > 0x2600 and ord(c) not in (0x2014, 0x2013, 0x2026)]
print(len(bad))
')
[ "$ZEROEMOJI" = "0" ] && pass "HTML contains no emoji glyphs" || fail "HTML has $ZEROEMOJI emoji glyph(s)"
PK="pico""bot"
check_not "html has no internal fleet paths" "$PK"                  "$HTML"
check_not "html has no private IPs"          "192.168."            "$HTML"
check_not "html has no ssh/sshpass"          "sshpass"             "$HTML"
check_not "html has no popen of shell"       "child_process"       "$HTML"

section "responsive markup"
check      "html has a 640px breakpoint"     '@media(max-width:640px)' "$HTML"
check      "html hides columns on mobile"    'hide-sm'              "$HTML"
check      "html grids use auto-fill"        'auto-fill,minmax'     "$HTML"
check      "html sparkline scales"           "preserveAspectRatio='none'" "$HTML"

section "no shell, no sockets"
SRCCAT=$(cat src/plugin_sysmon.c)
check_not "linux/mac code has no popen of user input" 'popen(\"ps' "$SRCCAT"
check_not "source opens no sockets"                   'socket('   "$SRCCAT"
check_not "source has no curl or wget"                'wget'      "$SRCCAT"
check_not "source has no ssh invocation"              'ssh '      "$SRCCAT"
check_not "source has no sshpass"                     'sshpass'   "$SRCCAT"

# ---------------------------------------------------------------- optional targets
section "optional cross builds"
if [ -f plugin_sysmon.musl ]; then
    M=$(./plugin_sysmon.musl --meta)
    check  "musl build --meta"              '"name":"sysmon"'       "$M"
    case $(head -c 4 plugin_sysmon.musl | od -An -tx1 | tr -d ' \n') in
        7f454c46) pass "musl artifact is ELF" ;;
        *) fail "musl artifact is not ELF" ;;
    esac
else
    echo "  skip musl (not built)"
fi
if [ -f plugin_sysmon.exe ]; then
    MAGIC=$(head -c 2 plugin_sysmon.exe)
    [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ"
    SZ=$(wc -c < plugin_sysmon.exe | tr -d ' ')
    [ "$SZ" -gt 20000 ] && pass "windows artifact is not an error page ($SZ bytes)" || fail "windows artifact suspiciously small ($SZ bytes)"
else
    echo "  skip windows PE (not built)"
fi
if [ -f plugin_sysmon.macos-arm64 ]; then
    MF=$(head -c 4 plugin_sysmon.macos-arm64 | od -An -tx1 | tr -d ' \n')
    case "$MF" in
        cffaedfe|feedfacf|cefaedfe|feedface) pass "macos-arm64 artifact is Mach-O" ;;
        *) fail "macos-arm64 artifact is not Mach-O ($MF)" ;;
    esac
else
    echo "  skip macos-arm64 (not built)"
fi
if [ -f plugin_sysmon.macos-x86_64 ]; then
    MF=$(head -c 4 plugin_sysmon.macos-x86_64 | od -An -tx1 | tr -d ' \n')
    case "$MF" in
        cffaedfe|feedfacf|cefaedfe|feedface) pass "macos-x86_64 artifact is Mach-O" ;;
        *) fail "macos-x86_64 artifact is not Mach-O ($MF)" ;;
    esac
else
    echo "  skip macos-x86_64 (not built)"
fi

# ---------------------------------------------------------------- history audit
section "git history secret & LAN audit"
if git rev-parse --git-dir >/dev/null 2>&1; then
    ALL=$(mktemp 2>/dev/null || echo /tmp/sysmon_hist_$$)
    # Bookkeeping lines of this audit are excluded so the detector cannot flag itself.
    git log -p --all 2>/dev/null \
      | grep -v '^Author: ' \
      | grep -vE 'audit "|HITS=|grep -E|scan "' \
      > "$ALL" || : > "$ALL"

    audit() { # audit <label> <regex>
        H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
        if [ -n "$H" ]; then
            fail "history: $1"; printf '%s\n' "$H" | sed 's/^/       /'
        else
            pass "history clean: $1"
        fi
    }
    audit "LAN 192.168.x"        '192\.168\.[0-9]+\.[0-9]+'
    audit "private 10.x"         '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
    audit "private 172.16-31.x"  '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
    audit "GitHub PAT"           'ghp_[A-Za-z0-9]{36}'
    audit "HuggingFace token"    'hf_[A-Za-z0-9]{30,}'
    audit "embedded git creds"   'scorpioxinc:[A-Za-z0-9]{20,}'
    # the literal is split so this file never contains the string it hunts
    audit "bare host password"   'Xbo''xone0909|xbo''xone'
    audit "hard-coded ssh password" 'sshpass -p [^"]$'
    PK="pico""bot"; WT=".work""trees"
    audit "fleet path"           "/codebases/${PK}|${WT}/"
    rm -f "$ALL"
else
    echo "  skip history audit (not a git checkout)"
fi

# ---------------------------------------------------------------- summary
printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
printf '  passed: %d\n' "$PASS"
printf '  failed: %d\n' "$FAIL"
if [ "$FAIL" -ne 0 ]; then
    printf '  %sRESULT: FAILED%s\n' "$C_BAD" "$C_0"
    exit 1
fi
printf '  %sRESULT: ALL PASSED%s\n' "$C_OK" "$C_0"
exit 0
