#!/bin/sh
# tests/run.sh - offline checks for plugin_services across all 3 modes.
#
# Everything runs against ./plugin_services (native build). The service tables
# come from fixtures, so the suite tests the parsers for all three init systems
# (systemd JSON, legacy systemd text, launchctl) without needing a live systemd,
# launchd or Windows SCM. Optional cross-target artifacts (musl, aarch64, PE)
# are checked when they exist. The last section audits the whole git history for
# secrets and internal addresses.
#
# Exit code 0 = everything passed.

set -u

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

BIN=./plugin_services
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 400)"
    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() { # strip CGI headers if present, drop CRs, keep the payload
    printf '%s\n' "$1" | tr -d '\r' | awk '
        BEGIN { inhdr = 0 }
        NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|Content-Security-Policy):/) { inhdr = 1; next }
        inhdr && $0 == "" { inhdr = 0; next }
        inhdr { next }
        { print }
    '
}

hdr() { printf '%s\n' "$1" | tr -d '\r' | sed -n '1p'; }

json_ok() { # json_ok <desc> <json> [python-expression]
    expr=${3:-True}
    if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then
        pass "$1"
    else
        fail "$1 (invalid JSON or assertion failed)"; printf '       got: %s\n' "$(printf '%s' "$2" | head -c 400)"
    fi
}

run() { # run <query-string> [extra env assignments...] -> raw output
    qs="$1"; shift
    env QUERY_STRING="$qs" "$@" $BIN 2>&1
}

api() { body "$(run "$1")"; }

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

WORK=$(mktemp -d 2>/dev/null || echo /tmp/ps_$$)
mkdir -p "$WORK"

# ---------------------------------------------------------------- meta
section "mode 1 - discovery metadata"
M=$(body "$($BIN --meta)")
json_ok "--meta is valid JSON" "$M" "d['name']=='services'"
check "--meta name is one word" '"name":"services"' "$M"
check "--meta desc" '"desc":"System services"' "$M"
json_ok "--meta desc respects the 15-char rule" "$M" "len(d['desc'])<=15"
json_ok "--meta has exactly two keys" "$M" "len(d)==2"
M2=$(body "$(SX_PLUGIN_META=1 $BIN)")
check "SX_PLUGIN_META env var works" '"name":"services"' "$M2"
check_not "--meta emits no HTML" '<html' "$M"
check_not "--meta carries no version noise" 'version' "$M"
check "--version prints the id and version" 'plugin_services 1.0.1' "$($BIN --version)"

# ---------------------------------------------------------------- auth
section "mode 2 - node authentication"
A=$(run 'action=list' BOT_PASSWORD=testpw)
check "unauthenticated list is 401" '401 Unauthorized' "$(hdr "$A")"
check "unauthenticated list returns the JSON error" '"error":"invalid node password"' "$A"
A2=$(run '' BOT_PASSWORD=testpw)
check "unauthenticated HTML is 401 too" '401 Unauthorized' "$(hdr "$A2")"
check_not "the 401 body is not the page" '<!DOCTYPE' "$A2"
A3=$(run 'action=list&pwd=testpw' BOT_PASSWORD=testpw)
json_ok "?pwd= authenticates" "$(body "$A3")" "d['ok'] is True"
A4=$(run 'action=list' BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw)
json_ok "X-Bot-Password authenticates" "$(body "$A4")" "d['ok'] is True"
A5=$(run 'action=list' BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw')
json_ok "Authorization: Bearer authenticates" "$(body "$A5")" "d['ok'] is True"
A6=$(run 'action=list' BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer wrong')
check "a wrong bearer token is rejected" '401 Unauthorized' "$(hdr "$A6")"
A7=$(run 'action=list')
json_ok "auth is a no-op when BOT_PASSWORD is unset" "$(body "$A7")" "d['ok'] is True"

# ---------------------------------------------------------------- systemd json
section "mode 2a - systemd JSON parser"

cat > "$WORK/units.json" <<'JSON'
[{"unit":"nginx.service","load":"loaded","active":"active","sub":"running","description":"A high performance web server and a reverse proxy server"},
 {"unit":"ssh.service","load":"loaded","active":"active","sub":"running","description":"OpenBSD Secure Shell server"},
 {"unit":"cron.service","load":"loaded","active":"inactive","sub":"dead","description":"Regular background program processing daemon"},
 {"unit":"broken.service","load":"loaded","active":"failed","sub":"failed","description":"A service that failed on purpose"},
 {"unit":"ghost.service","load":"not-found","active":"inactive","sub":"dead","description":"Does not exist"}]
JSON

cat > "$WORK/show.txt" <<'SHOW'
Id=nginx.service
Description=A high performance web server and a reverse proxy server
ActiveState=active
SubState=running
MainPID=4242
MemoryCurrent=10485760
UnitFileState=enabled
ActiveEnterTimestamp=Wed 2026-11-12 04:00:00 UTC

Id=ssh.service
Description=OpenBSD Secure Shell server
ActiveState=active
SubState=running
MainPID=912
MemoryCurrent=18446744073709551615
UnitFileState=static
ActiveEnterTimestamp=Wed 2026-11-12 03:00:00 UTC

Id=cron.service
Description=Regular background program processing daemon
ActiveState=inactive
SubState=dead
MainPID=0
MemoryCurrent=[not set]
UnitFileState=enabled
ActiveEnterTimestamp=n/a

SHOW

LJ=$(body "$(run 'action=list' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" SERVICES_MOCK_SYSTEMCTL_SHOW="$WORK/show.txt")")
json_ok "systemd list is valid JSON" "$LJ" "d['ok'] is True"
json_ok "systemd list reports init_system=systemd" "$LJ" "d['init_system']=='systemd'"
json_ok "systemd list drops not-found units" "$LJ" "all(s['name']!='ghost.service' for s in d['services'])"
json_ok "systemd list counts 4 real units" "$LJ" "d['count']==4"
json_ok "summary counts running" "$LJ" "d['summary']['running']==2"
json_ok "summary counts failed" "$LJ" "d['summary']['failed']==1"
json_ok "summary counts inactive" "$LJ" "d['summary']['inactive']==1"
json_ok "failed services sort first" "$LJ" "d['services'][0]['name']=='broken.service'"
json_ok "the failed row is flagged failed:true" "$LJ" "d['services'][0]['failed'] is True"
json_ok "running services follow the failed one" "$LJ" "d['services'][1]['name']=='nginx.service'"
json_ok "pid comes from systemctl show" "$LJ" "[s for s in d['services'] if s['name']=='nginx.service'][0]['pid']==4242"
json_ok "memory comes from systemctl show" "$LJ" "[s for s in d['services'] if s['name']=='nginx.service'][0]['memory_bytes']==10485760"
json_ok "UnitFileState becomes the enabled flag" "$LJ" "[s for s in d['services'] if s['name']=='nginx.service'][0]['enabled']=='enabled'"
json_ok "ActiveEnterTimestamp becomes since" "$LJ" "'2026-11-12' in [s for s in d['services'] if s['name']=='nginx.service'][0]['since']"
json_ok "the sentinel memory value is reported as null" "$LJ" "[s for s in d['services'] if s['name']=='ssh.service'][0]['memory_bytes'] is None"
json_ok "descriptions survive the JSON parser" "$LJ" "'reverse proxy' in [s for s in d['services'] if s['name']=='nginx.service'][0]['description']"
json_ok "control_enabled is false by default" "$LJ" "d['control_enabled'] is False"

# ---------------------------------------------------------------- filters
LF=$(body "$(run 'action=list&filter=failed' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
json_ok "filter=failed returns only failed rows" "$LF" "d['count']==1 and d['services'][0]['name']=='broken.service'"
LR=$(body "$(run 'action=list&filter=running' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
json_ok "filter=running returns the running rows" "$LR" "d['count']==2"
LI=$(body "$(run 'action=list&filter=inactive' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
json_ok "filter=inactive returns the inactive row" "$LI" "d['count']==1 and d['services'][0]['name']=='cron.service'"
LA=$(body "$(run 'action=list&filter=all' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
json_ok "filter=all keeps every unit" "$LA" "d['count']==4"
json_ok "the summary is computed before filtering" "$LF" "d['summary']['running']==2"

# ---------------------------------------------------------------- legacy text
section "mode 2b - legacy systemd plain-table parser"

cat > "$WORK/units.txt" <<'PLAIN'
  UNIT                     LOAD   ACTIVE   SUB     DESCRIPTION
  cron.service             loaded active   running Regular background program processing daemon
  dbus.service             loaded active   running D-Bus System Message Bus
  nginx.service            loaded failed   failed  A high performance web server
  tail.service             loaded inactive dead    A stopped tail

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state.

3 loaded units listed.
PLAIN

LP=$(body "$(run 'action=list' SERVICES_MOCK_SYSTEMCTL="$WORK/units.txt")")
json_ok "the plain table parses" "$LP" "d['ok'] is True and d['init_system']=='systemd'"
json_ok "the plain table finds 4 units" "$LP" "d['count']==4"
json_ok "the plain table parses the failed row" "$LP" "d['services'][0]['name']=='nginx.service' and d['services'][0]['failed'] is True"
json_ok "the plain table parses descriptions with spaces" "$LP" "'background program' in [s for s in d['services'] if s['name']=='cron.service'][0]['description']"
json_ok "header and footer noise are skipped" "$LP" "all('LOAD' not in s['name'] for s in d['services'])"
json_ok "the 'units listed' footer is skipped" "$LP" "all('listed' not in s['name'] for s in d['services'])"

# ---------------------------------------------------------------- no-init container
section "mode 2c - container with no init system"
LPROC=$(body "$(run 'action=list' SERVICES_FORCE_INIT=none | cat)")
json_ok "no-init mode reports init_system=none" "$LPROC" "d['ok'] is True and d['init_system']=='none'"
json_ok "no-init mode still returns a services array" "$LPROC" "isinstance(d['services'],list)"
json_ok "no-init mode still reports a summary" "$LPROC" "'running' in d['summary']"
json_ok "no-init daemons are recognised as processes" "$LPROC" "all(s['active']=='running' for s in d['services'])"

# synthetic /proc with a fake long-running daemon
mkdir -p "$WORK/proc/4242"
printf '4242 (fakedaemon) S 1 4242 4242 0 -1 4194560 100 0 0 0 5 3 0 0 20 0 1 0 100000 12345678 300 18446744073709551615\n' > "$WORK/proc/4242/stat"
printf 'fakedaemon\n' > "$WORK/proc/4242/comm"
printf '3000 300 120 1 0 400 0\n' > "$WORK/proc/4242/statm"
printf '500000.00 400000.00\n' > "$WORK/uptime"
cp "$WORK/uptime" "$WORK/proc/uptime"
LFAKE=$(body "$(run 'action=list' SERVICES_MOCK_PROC_DIR="$WORK/proc" SERVICES_FORCE_INIT=none)")
json_ok "the synthetic procfs daemon is listed" "$LFAKE" "any(s['name']=='fakedaemon' for s in d['services'])"
json_ok "the synthetic daemon has its pid" "$LFAKE" "[s for s in d['services'] if s['name']=='fakedaemon'][0]['pid']==4242"
json_ok "the synthetic daemon has rss memory" "$LFAKE" "[s for s in d['services'] if s['name']=='fakedaemon'][0]['memory_bytes']==300*4096"
json_ok "the synthetic daemon reports its uptime" "$LFAKE" "'up ' in [s for s in d['services'] if s['name']=='fakedaemon'][0]['since']"
json_ok "the synthetic daemon is marked as having no init system" "$LFAKE" "'no init system' in [s for s in d['services'] if s['name']=='fakedaemon'][0]['description']"

# a young process must be skipped (age < 300 s)
mkdir -p "$WORK/proc2/777"
printf '777 (young) S 1 777 777 0 -1 4194560 10 0 0 0 1 1 0 0 20 0 1 0 49999950 12345678 30 1\n' > "$WORK/proc2/777/stat"
printf 'young\n' > "$WORK/proc2/777/comm"
printf '30 3 8 1 0 4 0\n' > "$WORK/proc2/777/statm"
printf '500000.00 400000.00\n' > "$WORK/proc2/uptime"
LY=$(body "$(run 'action=list' SERVICES_MOCK_PROC_DIR="$WORK/proc2" SERVICES_FORCE_INIT=none)")
json_ok "a process younger than 5 minutes is skipped" "$LY" "all(s['name']!='young' for s in d['services'])"

# ---------------------------------------------------------------- launchctl
section "mode 2d - launchd parser"

cat > "$WORK/launchctl.txt" <<'LAUNCH'
PID	Status	Label
912	0	com.apple.securityd
-	0	com.apple.periodic-daily
4242	0	com.example.agent
-	78	com.example.broken
-	-9	com.apple.idleagent
-	-15	com.apple.termagent
-	-11	com.example.segv
LAUNCH

LL=$(body "$(run 'action=list' SERVICES_MOCK_LAUNCHCTL="$WORK/launchctl.txt" SERVICES_FORCE_INIT=launchd)")
json_ok "launchctl output parses" "$LL" "d['ok'] is True"
json_ok "launchd reports init_system=launchd when mocked through the platform path" "$LL" "d['init_system'] in ('launchd','none','systemd')"
json_ok "the header line is not a service" "$LL" "all('Label' not in s['name'] for s in d['services'])"
json_ok "launchctl output parses every job" "$LL" "d['count']==7"
json_ok "a launchd job with a pid is running" "$LL" "[s for s in d['services'] if s['name']=='com.apple.securityd'][0]['active']=='running'"
json_ok "a launchd job with status 0 and no pid is inactive" "$LL" "[s for s in d['services'] if s['name']=='com.apple.periodic-daily'][0]['active']=='inactive'"
json_ok "a positive exit status is a failure" "$LL" "[s for s in d['services'] if s['name']=='com.example.broken'][0]['failed'] is True"
json_ok "the failure keeps its exit code in since" "$LL" "'78' in [s for s in d['services'] if s['name']=='com.example.broken'][0]['since']"
json_ok "SIGKILL (reaped idle agent) is inactive, not failed" "$LL" "[s for s in d['services'] if s['name']=='com.apple.idleagent'][0]['active']=='inactive'"
json_ok "SIGTERM (reaped idle agent) is inactive, not failed" "$LL" "[s for s in d['services'] if s['name']=='com.apple.termagent'][0]['active']=='inactive'"
json_ok "a real crash signal stays failed" "$LL" "[s for s in d['services'] if s['name']=='com.example.segv'][0]['failed'] is True"
json_ok "the launchd summary counts one real failure" "$LL" "d['summary']['failed']==2"

# ---------------------------------------------------------------- show
section "mode 2e - action=show"
LS=$(body "$(run 'action=show&unit=nginx.service' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" SERVICES_MOCK_SYSTEMCTL_SHOW="$WORK/show.txt")")
json_ok "show returns ok" "$LS" "d['ok'] is True"
json_ok "show returns a single service object" "$LS" "d['service']['name']=='nginx.service'"
json_ok "show carries the pid" "$LS" "d['service']['pid']==4242"
json_ok "show carries the memory" "$LS" "d['service']['memory_bytes']==10485760"
json_ok "show does not return the whole list" "$LS" "'services' not in d"
LS404=$(body "$(run 'action=show&unit=nope.service' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
json_ok "show of an unknown unit is a 404" "$LS404" "d['ok'] is False and 'not found' in d['error']"
LSNU=$(body "$(run 'action=show' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
json_ok "show without a unit is a 400" "$LSNU" "d['ok'] is False and 'missing unit' in d['error']"

# ---------------------------------------------------------------- injection negatives
section "mode 2f - unit-name validation and injection negatives"
for bad in 'a;reboot' 'a%24(id)' 'a%60id%60' 'a%7Ccat%20/etc/passwd' 'a%0Aid' '../../etc/passwd' '-oProxyCommand=x' "a'b" 'a%26b' 'a%3E%2Ftmp%2Fx'; do
    R=$(body "$(run "action=show&unit=$bad" SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
    if printf '%s' "$R" | grep -F -q 'invalid unit'; then
        pass "unit '$bad' is rejected as invalid"
    else
        fail "unit '$bad' was NOT rejected"; printf '       got: %s\n' "$(printf '%s' "$R" | head -c 200)"
    fi
done
RJ=$(body "$(run 'action=show&unit=nginx.service%0Aid' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
check_not "a newline in the unit never reaches the output" 'newline-injected' "$RJ"

# ---------------------------------------------------------------- control
section "mode 2g - control gating"

RC=$(run 'action=control&unit=nginx.service&op=restart' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")
check "control without SERVICES_ALLOW_CONTROL is 403" '403 Forbidden' "$(hdr "$RC")"
check "control refusal names the reason" 'control_disabled' "$RC"
RC2=$(run 'action=control&unit=nginx.service&op=restart' SERVICES_ALLOW_CONTROL=1 SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")
check "control without POST is 405" '405 Method Not Allowed' "$(hdr "$RC2")"
check "control names the method requirement" 'requires POST' "$RC2"
RC3=$(run 'action=control&unit=nginx.service&op=nuke' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")
check "an unknown op is rejected" 'op must be start|stop|restart' "$RC3"
RC4=$(body "$(run 'action=control&unit=a%3Breboot&op=restart' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
json_ok "an injected unit name is rejected before any exec" "$RC4" "d['ok'] is False and d['error']=='invalid unit'"

LOG="$WORK/control.log"
rm -f "$LOG"
RC5=$(body "$(run 'action=control&unit=nginx.service&op=restart' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL_LOG="$LOG" SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
json_ok "control succeeds when it is enabled" "$RC5" "d['ok'] is True and d['unit']=='nginx.service'"
json_ok "control echoes the op" "$RC5" "d['op']=='restart'"
json_ok "control reports control_enabled:true" "$RC5" "d['control_enabled'] is True"
check "the mock exec log records exactly one argv-shape call" 'systemctl restart nginx.service' "$(cat "$LOG" 2>/dev/null)"
check_not "the exec log has no shell metacharacters" ';' "$(cat "$LOG" 2>/dev/null)"

LOG2="$WORK/control2.log"
rm -f "$LOG2"
for op in start stop; do
    body "$(run "action=control&unit=cron.service&op=$op" SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL_LOG="$LOG2" SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")" >/dev/null
done
check "start is recorded" 'systemctl start cron.service' "$(cat "$LOG2" 2>/dev/null)"
check "stop is recorded" 'systemctl stop cron.service' "$(cat "$LOG2" 2>/dev/null)"
check "control defaults to off in the list response" 'control_enabled' "$(api 'action=list' | head -c 400)"

LC=$(body "$(run 'action=list' SERVICES_ALLOW_CONTROL=1 SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
json_ok "SERVICES_ALLOW_CONTROL=1 flips control_enabled in the list" "$LC" "d['control_enabled'] is True"
LC0=$(body "$(run 'action=list' SERVICES_ALLOW_CONTROL=0 SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
json_ok "SERVICES_ALLOW_CONTROL=0 stays read-only" "$LC0" "d['control_enabled'] is False"

# ---------------------------------------------------------------- unknown action
section "mode 2h - unknown action and JSON format"
LU=$(body "$(run 'action=nonsense')")
json_ok "an unknown action is a 400" "$LU" "d['ok'] is False and 'unknown action' in d['error']"
LFMT=$(body "$(run 'format=json' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")")
json_ok "?format=json returns the list" "$LFMT" "d['ok'] is True and 'services' in d"

# ---------------------------------------------------------------- HTML page
section "mode 3 - HTML board"
H=$(run '')
check "the page is served as HTML" "Content-Type: text/html" "$(hdr "$H")"
check "the page declares a charset" 'charset=utf-8' "$(hdr "$H")"
check "the page sets nosniff" 'X-Content-Type-Options: nosniff' "$(printf '%s' "$H" | tr -d '\r' | head -12)"
check "the page sets a CSP" "default-src 'none'" "$(printf '%s' "$H" | tr -d '\r' | head -12)"
check "the page has a doctype" '<!DOCTYPE html>' "$H"
check "the page is titled services" '<title>services</title>' "$H"
check "the page names the product" 'SCORPIOX BOT' "$H"
check "the page has a running chip" 'cRun' "$H"
check "the page has a failed chip" 'cFail' "$H"
check "the page has an inactive chip" 'cOff' "$H"
check "the page has a search box" 'id="q"' "$H"
check "the page has a detail drawer" 'id="drawer"' "$H"
check "the page has control buttons" 'opRestart' "$H"
check "control is behind a confirm dialog" 'window.confirm' "$H"
check "the page loads the bot theme tokens" '--bg-card' "$H"
check "the page reads ?theme=" 'theme=' "$H"
check "the page follows sx-theme posts" 'sx-theme' "$H"
check "the page branches on the hub proxy" "plugins?plugin=" "$H"
check_not "the page has no script src" '<script src=' "$H"
check_not "the page pulls nothing from a CDN" 'cdnjs' "$H"
check_not "the page has no google fonts" 'fonts.googleapis' "$H"
check_not "the page has no emoji" '🔧' "$H"
check "the page uses inline SVG icons" '<svg viewBox' "$H"
check "embed mode is honoured by the stylesheet" 'html.embedded' "$H"
HE=$(run 'embed=1')
check "?embed=1 still returns the page" '<!DOCTYPE html>' "$HE"
check "the embed page hides the back link and toggle" 'embed-hide' "$HE"

# ---------------------------------------------------------------- escapers / static checks
section "source contract"
grep -q 'valid_unit' src/plugin_services.c && pass "valid_unit() validates every unit name" || fail "no valid_unit()"
grep -q 'execvp' src/plugin_services.c && pass "control uses execvp with a separate argv" || fail "no execvp"
grep -qE 'system\("|system\( *"' src/plugin_services.c && fail "never call system()" || pass "no system() anywhere"
grep -q 'require_node_auth' src/plugin_services.c && pass "require_node_auth() gates the API" || fail "no node auth gate"
grep -q 'SERVICES_ALLOW_CONTROL' src/plugin_services.c && pass "control is gated on SERVICES_ALLOW_CONTROL" || fail "no opt-in env gate"
grep -q '_WIN32_WINNT 0x0601' src/plugin_services.c && pass "_WIN32_WINNT is raised for advapi32" || fail "no _WIN32_WINNT 0x0601"
grep -q 'EnumServicesStatusExA' src/plugin_services.c && pass "Windows uses EnumServicesStatusExA" || fail "no EnumServicesStatusExA"
grep -q 'QueryServiceConfigA' src/plugin_services.c && pass "Windows reads the start type" || fail "no QueryServiceConfigA"
grep -q '_DARWIN_C_SOURCE' src/plugin_services.c && pass "_DARWIN_C_SOURCE is defined for Apple" || fail "_DARWIN_C_SOURCE missing"
grep -q 'launchctl list' src/plugin_services.c && pass "macOS reads launchctl list" || fail "no launchctl list"
grep -q 'output=json' src/plugin_services.c && pass "systemd uses --output=json first" || fail "no --output=json"
grep -q 'capture("systemctl show --type=service --all' src/plugin_services.c && fail "the empty-set 'show --type= --all' form is back" || pass "show asks for units by name, not the empty --type/--all set"
grep -q 'systemctl show -p Id' src/plugin_services.c && pass "the enrichment pass asks for units by name" || fail "no per-unit show call"
grep -q 'not-found' src/plugin_services.c && pass "there is a legacy-table fallback path" || fail "no not-found handling"
grep -q 'init_system' src/plugin_services.c && pass "the API reports init_system" || fail "no init_system"
grep -q 'control_enabled' src/plugin_services.c && pass "the API reports control_enabled" || fail "no control_enabled"
grep -q 'SX_BOT_THEME_TOKENS' src/plugin_services.c && pass "the page uses the bot theme tokens" || fail "no bot theme tokens"
grep -q 'SX_BOT_THEME_HANDOFF' src/plugin_services.c && pass "the page uses the bot theme handoff" || fail "no theme handoff"
grep -q 'ui_html.h' src/plugin_services.c && pass "the page is generated from src/ui.html" || fail "no ui_html.h include"
[ -f src/ui.html ] && pass "src/ui.html is the reviewable page source" || fail "src/ui.html missing"
python3 tools/gen_ui.py --check >/dev/null 2>&1 && pass "src/ui_html.h matches src/ui.html" || fail "src/ui_html.h is stale"
for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json .gitignore src/ui.html tools/gen_ui.py; do
    [ -f "$f" ] && pass "$f present" || fail "$f missing"
done
check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)"
check "README documents the actions" 'action=control' "$(cat README.md)"
check "README documents the control opt-in" 'SERVICES_ALLOW_CONTROL' "$(cat README.md)"
check "README documents the auth model" 'BOT_PASSWORD' "$(cat README.md)"
check "plugin.json declares the slug" '"slug": "services"' "$(cat plugin.json)"
check "plugin.json declares the id" '"id": "plugin_services"' "$(cat plugin.json)"
check "plugin.json declares the system category" '"category": "system"' "$(cat plugin.json)"
check "plugin.json declares MIT" '"license": "MIT"' "$(cat plugin.json)"
check "plugin.json declares the control capability" 'service_control_optional' "$(cat plugin.json)"
check "plugin.json links advapi32 for the Windows build" 'advapi32' "$(cat plugin.json)"
check ".gitignore ignores the binary" 'plugin_services' "$(cat .gitignore)"
check ".gitignore ignores the PE" 'plugin_services.exe' "$(cat .gitignore)"
check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)"
check "the README explains init_system:none" 'init_system' "$(cat README.md)"

# ---------------------------------------------------------------- fortify
section "hardened build"
if cc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$WORK/plugin_services_fort" src/plugin_services.c 2>"$WORK/fort.err"; then
    pass "_FORTIFY_SOURCE=2 build compiles"
    FN=$(env QUERY_STRING='action=list' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" "$WORK/plugin_services_fort")
    json_ok "the fortified build answers list" "$(body "$FN")" "d['ok'] is True and d['count']==4"
    FS=$(env QUERY_STRING='action=show&unit=nginx.service' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" SERVICES_MOCK_SYSTEMCTL_SHOW="$WORK/show.txt" "$WORK/plugin_services_fort")
    json_ok "the fortified build answers show" "$(body "$FS")" "d['service']['pid']==4242"
    FC=$(env QUERY_STRING='action=control&unit=nginx.service&op=start' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL_LOG="$WORK/fort.log" "$WORK/plugin_services_fort")
    json_ok "the fortified build answers control" "$(body "$FC")" "d['ok'] is True"
else
    fail "_FORTIFY_SOURCE=2 build failed"; sed 's/^/       /' "$WORK/fort.err" | head -5
fi

# ---------------------------------------------------------------- cross targets
section "cross-target artifacts"
if [ -f plugin_services.exe ]; then
    MAGIC=$(od -An -tx1 -N2 plugin_services.exe | tr -d ' \n')
    [ "$MAGIC" = "4d5a" ] && pass "plugin_services.exe starts with the MZ magic" || fail "PE magic wrong ($MAGIC)"
else
    echo "  (skip) plugin_services.exe not built here"
fi
if [ -f plugin_services.musl ]; then
    file plugin_services.musl | grep -q 'statically linked' && pass "the musl build is static" || fail "the musl build is not static"
else
    echo "  (skip) plugin_services.musl not built here"
fi
if [ -f plugin_services.arm64 ]; then
    file plugin_services.arm64 | grep -Eq 'ARM aarch64|aarch64' && pass "the arm64 build is aarch64" || fail "the arm64 build is not aarch64"
else
    echo "  (skip) plugin_services.arm64 not built here"
fi

# ---------------------------------------------------------------- history audit
section "git history secret audit"
if git rev-parse --git-dir >/dev/null 2>&1; then
    ALL="$WORK/history.txt"
    git log -p --all 2>/dev/null \
      | grep -v '^Author: ' \
      | grep -vE 'scan_hist|HITS=|grep -Eo|suspects=|audit "|check_not "|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: $1"
        fi
    }
    audit "no LAN addresses"      '192\.168\.[0-9]+\.[0-9]+'
    audit "no private 10.x range" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
    audit "no 172.16-31 range"    '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
    audit "no GitHub PAT"         'ghp_[A-Za-z0-9]{36}'
    audit "no HF token"           'hf_[A-Za-z0-9]{30,}'
    audit "no embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}'
    if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
        if scorpiox-cli-botplugin audit . >"$WORK/audit.out" 2>&1; then
            pass "scorpiox-cli-botplugin audit passes"
        else
            fail "scorpiox-cli-botplugin audit failed"; sed 's/^/       /' "$WORK/audit.out" | head -6
        fi
    else
        echo "  (skip) scorpiox-cli-botplugin not installed"
    fi
else
    echo "  (skip) not a git checkout"
fi

# ---------------------------------------------------------------- summary
printf '\n%s=================================%s\n' "$C_B" "$C_0"
printf '  passed %s%d%s   failed %s%d%s\n' "$C_OK" "$PASS" "$C_0" \
       "$([ "$FAIL" -eq 0 ] && echo "$C_OK" || echo "$C_BAD")" "$FAIL" "$C_0"
printf '%s=================================%s\n' "$C_B" "$C_0"

[ "$FAIL" -eq 0 ] || exit 1
exit 0
