#!/bin/sh
# tests/run.sh - offline checks for plugin_disks across all 3 modes.
#
# Runs against ./plugin_disks (native build) on the live machine, so the mount
# assertions use this node's real /proc/mounts (or getmntinfo / Win32 drive
# list). If a musl static build or a Windows PE (plugin_disks.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_disks
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'; }

TMP=$(mktemp -d 2>/dev/null || echo /tmp/disks_tests_$$)
mkdir -p "$TMP" 2>/dev/null || true

# ---------------------------------------------------------------- build
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    cc -O2 -std=c99 -Wall -Wextra -o "$BIN" src/plugin_disks.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 disks"         '"name":"disks"'         "$META"
check      "meta emits desc Local storage" '"desc":"Local storage"' "$META"
METAENV=$(SX_PLUGIN_META=1 "$BIN")
check      "SX_PLUGIN_META=1 yields same meta" '"name":"disks"'     "$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":"disks"' "$META_AUTH"

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

# ---------------------------------------------------------------- mounts
section "mode 2 action=mounts"
MF="$TMP/mounts.json"
MOUNTS=$(body "$(QUERY_STRING='action=mounts' "$BIN")")
printf '%s' "$MOUNTS" > "$MF"
check      "mounts ok:true"                 '"ok":true'             "$MOUNTS"
check      "mounts names the plugin"        '"plugin":"plugin_disks"' "$MOUNTS"
check      "mounts declares platform"       '"platform":"'          "$MOUNTS"
check      "mounts declares zero_network"   '"zero_network":true'   "$MOUNTS"
check      "mounts carries a utc stamp"     '"utc":"20'             "$MOUNTS"
check      "mounts lists an array"          '"mounts":['            "$MOUNTS"
printf '%s' "$MOUNTS" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
    && pass "mounts body is valid JSON" || fail "mounts body JSON invalid"

python3 - "$MF" <<'PY' && pass "mount rows are well formed" || fail "mount rows malformed"
import json, sys
d = json.load(open(sys.argv[1]))
assert d["count"] == len(d["mounts"])
for m in d["mounts"]:
    assert isinstance(m["device"], str)
    assert isinstance(m["fstype"], str)
    assert isinstance(m["mount"], str) and m["mount"]
    for k in ("total_bytes", "used_bytes", "free_bytes", "avail_bytes"):
        assert isinstance(m[k], int) and m[k] >= 0, (k, m[k])
    assert 0.0 <= m["pct"] <= 100.0
PY

python3 - "$MF" <<'PY' && pass "no pseudo filesystems leaked into the table" || fail "pseudo fs present"
import json, sys
d = json.load(open(sys.argv[1]))
banned = {"proc","sysfs","cgroup","cgroup2","devpts","devtmpfs","debugfs",
          "tracefs","securityfs","pstore","bpf","mqueue","configfs"}
got = {m["fstype"] for m in d["mounts"]} & banned
assert not got, got
PY

python3 - "$MF" <<'PY' && pass "no kernel mountpoints leaked into the table" || fail "kernel mountpoint present"
import json, sys
d = json.load(open(sys.argv[1]))
bad = [m["mount"] for m in d["mounts"]
       if m["mount"].startswith(("/sys", "/proc", "/dev"))]
assert not bad, bad
PY

python3 - "$MF" <<'PY' && pass "mountpoints are unique (no double counting)" || fail "duplicate mountpoint"
import json, sys
d = json.load(open(sys.argv[1]))
mp = [m["mount"] for m in d["mounts"]]
assert len(mp) == len(set(mp)), [x for x in mp if mp.count(x) > 1]
PY

python3 - "$MF" <<'PY' && pass "mounts are ordered largest first" || fail "mount order wrong"
import json, sys
d = json.load(open(sys.argv[1]))
t = [m["total_bytes"] for m in d["mounts"]]
assert t == sorted(t, reverse=True), t
PY

# The live root filesystem must always be reported on POSIX, whichever node runs it.
python3 - "$MF" <<'PY' && pass "live root mount is reported" || fail "root mount missing"
import json, sys, os
d = json.load(open(sys.argv[1]))
if os.name != "nt":
    roots = [m for m in d["mounts"] if m["mount"] == "/"]
    assert roots, "no / mount"
    assert roots[0]["total_bytes"] > 0
PY

python3 - "$MF" <<'PY' && pass "used + avail never exceeds the reported total by much" || fail "usage math inconsistent"
import json, sys
d = json.load(open(sys.argv[1]))
for m in d["mounts"]:
    # reserved blocks may make used+avail < total; they must never exceed it
    assert m["used_bytes"] + m["avail_bytes"] <= m["total_bytes"] + 1
PY

python3 - "$MF" <<'PY' && pass "info/supported keys reachable via format=json" || fail "format=json alias broken"
import json, sys
PY
check      "format=json aliases to mounts"  '"action":"mounts"'     "$(body "$(QUERY_STRING='format=json' "$BIN")")"
rm -f "$MF"

# ---------------------------------------------------------------- dirs
section "mode 2 action=dirs - allowlist and traversal rejection"
for bad in etc /etc .. ../.. workspace/ /workspace /root /home workspace\\ $'workspace\n' '%2Fetc' ; do
    R=$(body "$(QUERY_STRING="action=dirs&root=$(printf '%s' "$bad" | sed 's/ /%20/g')" "$BIN")")
    if printf '%s' "$R" | grep -F -q '"ok":false'; then
        pass "root rejected: $bad"
    else
        fail "root accepted: $bad -> $R"
    fi
done
MISS=$(body "$(QUERY_STRING='action=dirs' "$BIN")")
check      "missing root rejected"          'missing_root'          "$MISS"
check      "missing root lists the allowlist" '"allowed_roots":["workspace","home"]' "$MISS"
TRAV=$(body "$(QUERY_STRING='action=dirs&root=/etc' "$BIN")")
check      "traversal rejection is explicit" 'root_not_allowed'      "$TRAV"
check      "traversal rejection echoes input" '"requested":"/etc"'  "$TRAV"

section "mode 2 action=dirs - real roots"
DH=$(body "$(QUERY_STRING='action=dirs&root=home' "$BIN")")
DF="$TMP/home.json"
printf '%s' "$DH" > "$DF"
if printf '%s' "$DH" | grep -F -q '"ok":true'; then
    pass "home root scans on this node"
    check  "dirs echoes the root kind"      '"root_kind":"home"'    "$DH"
    check  "dirs labels the root"           '"root_label":"$HOME"'  "$DH"
    check  "dirs declares max depth"        '"max_depth":'          "$DH"
    check  "dirs declares the scan budget"  '"max_scan_entries":'   "$DH"
    check  "dirs reports the scan time"     '"scan_ms":'            "$DH"
    check  "dirs reports truncation state"  '"truncated":'          "$DH"
    python3 - "$DF" <<'PY' && pass "dir rows are well formed" || fail "dir rows malformed"
import json, sys
d = json.load(open(sys.argv[1]))
assert d["count"] == len(d["entries"])
for e in d["entries"]:
    assert isinstance(e["name"], str) and e["name"]
    assert isinstance(e["path"], str) and e["path"]
    assert isinstance(e["bytes"], int) and e["bytes"] >= 0
    assert isinstance(e["is_dir"], bool)
    assert 0.0 <= e["pct"] <= 100.0
PY
    python3 - "$DF" <<'PY' && pass "dir entries are ordered largest first" || fail "dir order wrong"
import json, sys
d = json.load(open(sys.argv[1]))
b = [e["bytes"] for e in d["entries"]]
assert b == sorted(b, reverse=True), b
PY
    python3 - "$DF" <<'PY' && pass "dir scan stays inside the requested root" || fail "entry escaped the root"
import json, sys, os
d = json.load(open(sys.argv[1]))
root = d["root"].rstrip("/") + "/"
for e in d["entries"]:
    assert e["path"].startswith(root), e["path"]
PY
    python3 - "$DF" <<'PY' && pass "dir scan is bounded (entry count within the cap)" || fail "entry cap exceeded"
import json, sys
d = json.load(open(sys.argv[1]))
assert d["count"] <= 512, d["count"]
PY
else
    pass "home root unavailable on this node (root_unavailable is a valid answer)"
    check "unavailable root is not an error leak" 'root_unavailable' "$DH"
fi
rm -f "$DF"

DW=$(body "$(QUERY_STRING='action=dirs&root=workspace' "$BIN")")
if printf '%s' "$DW" | grep -F -q '"ok":true'; then
    pass "workspace root scans on this node"
    check "workspace echoes its kind" '"root_kind":"workspace"' "$DW"
elif printf '%s' "$DW" | grep -F -q 'root_unavailable'; then
    pass "workspace root absent on this node (reported as root_unavailable)"
else
    fail "workspace root gave neither data nor root_unavailable: $DW"
fi

# ---------------------------------------------------------------- info + unknown
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 allowed_roots declared"    '"allowed_roots":["workspace","home"]' "$IBODY"
check      "info max_depth declared"        '"max_depth":8'         "$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"

UNK=$(QUERY_STRING='action=bogus' "$BIN")
check      "unknown action rejected"        'unknown_action'        "$(body "$UNK")"
check      "unknown action lists supported" '"supported":["mounts","dirs","info"]' "$(body "$UNK")"
check      "unknown action echoes request"  '"requested":"bogus"'   "$(body "$UNK")"

# ---------------------------------------------------------------- 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 disks"               '<title>disks</title>'  "$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 mount host present"        "id='mounts'"           "$HTML"
check      "html folder table host"         "id='rows'"             "$HTML"
check      "html root segmented control"    'data-root='            "$HTML"
check      "html rate segmented control"    'data-ms='              "$HTML"
check      "html capacity bar element"      "el('div','bar')"       "$HTML"
check      "html calls the mounts action"   "base('mounts')"        "$HTML"
check      "html calls the dirs action"     "base('dirs')"          "$HTML"
check      "html uses /plugins?plugin= route" "/plugins?plugin="    "$HTML"
check      "html falls back to /plugin_disks" "/plugin_disks"       "$HTML"
check      "html closes document"           '</html>'               "$HTML"
check      "html declares zero network"     'zero outbound network' "$HTML"
check      "html shows the inode column"    'inodes'                "$HTML"
check      "html colour-codes over-75%"     'warn'                  "$HTML"
check      "html colour-codes over-90%"     'danger'                "$HTML"
EMB=$(QUERY_STRING='embed=1' "$BIN")
check      "embed=1 still renders the UI"   "id='mounts'"           "$EMB"
check_not  "embed=1 drops the direct-open note" 'Opened directly from the node API' "$EMB"
EMBT=$(QUERY_STRING='embed=true' "$BIN")
check_not  "embed=true also drops the note" 'Opened directly from the node API' "$EMBT"
EMBN=$(QUERY_STRING='' "$BIN")
check      "non-embed keeps the note"       'Opened directly from the node API' "$EMBN"

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"

section "responsive markup"
check      "html has a narrow breakpoint"    '@media(max-width:560px)' "$HTML"
check      "html hides columns on mobile"    'hide-sm'              "$HTML"
check      "html grids use auto-fit"         'auto-fit,minmax'      "$HTML"

section "no shell, no sockets, no remote access"
SRCCAT=$(cat src/plugin_disks.c)
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"
check_not "source runs no popen"                      'popen('    "$SRCCAT"
check_not "source has no system()"                    'system('   "$SRCCAT"
check      "source walks with opendir/readdir"        'readdir'   "$SRCCAT"
check      "source uses statvfs on linux"             'statvfs'   "$SRCCAT"
check      "source refuses to follow symlinks"        'S_ISLNK'   "$SRCCAT"
check      "source caps the walk depth"               'MAX_DEPTH' "$SRCCAT"

# ---------------------------------------------------------------- optional targets
section "optional cross builds"
if [ -f plugin_disks.musl ]; then
    M=$(./plugin_disks.musl --meta)
    check  "musl build --meta"              '"name":"disks"'       "$M"
    case $(head -c 4 plugin_disks.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_disks.arm64 ]; then
    case $(head -c 4 plugin_disks.arm64 | od -An -tx1 | tr -d ' \n') in
        7f454c46) pass "arm64 artifact is ELF" ;;
        *) fail "arm64 artifact is not ELF" ;;
    esac
    # e_machine sits at offset 18, little endian: b7 00 == EM_AARCH64
    EM=$(od -An -tx1 -j 18 -N 2 plugin_disks.arm64 | tr -d ' \n')
    [ "$EM" = "b700" ] && pass "arm64 artifact declares EM_AARCH64" \
        || fail "arm64 artifact e_machine is $EM, expected b700"
else
    echo "  skip arm64 (not built)"
fi
if [ -f plugin_disks.exe ]; then
    MAGIC=$(head -c 2 plugin_disks.exe)
    [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ"
    SZ=$(wc -c < plugin_disks.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
for slice in arm64 x86_64; do
    f="plugin_disks.macos-$slice"
    if [ -f "$f" ]; then
        MF=$(head -c 4 "$f" | od -An -tx1 | tr -d ' \n')
        case "$MF" in
            cffaedfe|feedfacf|cefaedfe|feedface) pass "macos-$slice artifact is Mach-O" ;;
            *) fail "macos-$slice artifact is not Mach-O ($MF)" ;;
        esac
    else
        echo "  skip macos-$slice (not built)"
    fi
done

# ---------------------------------------------------------------- history audit
section "git history secret & LAN audit"
if git rev-parse --git-dir >/dev/null 2>&1; then
    ALL="$TMP/history.txt"
    # 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 "|P_ROOT=|P_WT=' \
      > "$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'
    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

rm -rf "$TMP"

# ---------------------------------------------------------------- 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
