#!/bin/sh
# tests/run.sh — 60+ offline checks for plugin_docker across all 3 modes.
#
# Runs against ./plugin_docker (native build) using a mock DOCKER_BIN script, so
# nothing here needs a real container runtime. If a musl static build or a
# Windows PE (plugin_docker.exe) is present, they are checked too. The whole git
# history is finally audited for secrets, PATs and LAN IPs.
#
# Exit code 0 = everything passed.

set -u

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

BIN=./plugin_docker
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'; }

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

# mock runtime
MOCKDIR=$(mktemp -d 2>/dev/null || echo /tmp/pd_mock_$$)
mkdir -p "$MOCKDIR"
MOCK="$MOCKDIR/mockdocker"
cat > "$MOCK" <<'MOCKEOF'
#!/bin/sh
case "$1" in
  ps)
    echo "a1b2c3d4e5f6|web|nginx:1.27|running|Up 3 hours|0.0.0.0:8080->80/tcp"
    echo "b2c3d4e5f6a1|db|postgres:16|running|Up 3 hours|127.0.0.1:5432->5432/tcp"
    echo "c3d4e5f6a1b2|old-job|alpine:3.20|exited|Exited (0) 2 days ago|"
    exit 0 ;;
  stats)
    echo "a1b2c3d4e5f6|1.25%|12.5MiB / 1GiB"
    echo "b2c3d4e5f6a1|0.40%|88.1MiB / 1GiB"
    exit 0 ;;
  logs)
    echo "line one"
    echo 'line two with "quotes" and a <tab>'
    printf 'line three\n'
    exit 0 ;;
  start|stop|restart)
    exit 0 ;;
  *) echo "unknown command: $1" >&2; exit 1 ;;
esac
MOCKEOF
chmod +x "$MOCK"

# a "no runtime" path: empty DOCKER_BIN, PATH with no docker/podman
# (no runtime helper: assignments are inlined at each call site)

# ---------------------------------------------------------------- meta mode
section "mode 1 --meta (must work without auth — discovery)"
META=$("$BIN" --meta)
check      "meta emits name docker"        '"name":"docker"'   "$META"
check      "meta emits desc Containers"    '"desc":"Containers"' "$META"
METAENV=$(SX_PLUGIN_META=1 "$BIN")
check      "SX_PLUGIN_META=1 yields same meta" '"name":"docker"' "$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.1.3'             "$("$BIN" --version)"
check      "--help is available"           'usage:'            "$("$BIN" --help)"

# ---------------------------------------------------------------- list mode
section "node auth"
AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=list' "$BIN")
check      "no credentials -> 401"         'Status: 401'        "$AUTHNONE"
check      "401 body is json error"        'invalid node password' "$AUTHNONE"
check_not  "401 leaks no container data"   '"containers"'       "$AUTHNONE"
AUTHBAD=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=list' "$BIN")
check      "wrong header password -> 401"  'Status: 401'        "$AUTHBAD"
AUTHHDR=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=list' "$BIN")
check      "X-Bot-Password accepted"       '"ok":true'          "$(body "$AUTHHDR")"
AUTHBEAR=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=list' "$BIN")
check      "Authorization Bearer accepted" '"ok":true'          "$(body "$AUTHBEAR")"
AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=list&pwd=testpw' "$BIN")
check      "?pwd= accepted"                '"ok":true'          "$(body "$AUTHQ")"
AUTHHTML=$(BOT_PASSWORD=testpw QUERY_STRING='' "$BIN")
check      "html page requires auth too"   'Status: 401'        "$AUTHHTML"
AUTHMETA=$(BOT_PASSWORD=testpw "$BIN" --meta)
check      "--meta succeeds without auth"  '"name":"docker"'    "$AUTHMETA"
AUTHOPEN=$(QUERY_STRING='action=list' "$BIN")
check      "unset BOT_PASSWORD = open node" 'Content-Type: application/json' "$AUTHOPEN"

# All remaining checks run with BOT_PASSWORD unset (open mode) so they stay readable.
section "mode 2 JSON list (mock runtime)"
export DOCKER_BIN="$MOCK"
LIST=$(QUERY_STRING='action=list' "$BIN")
LBODY=$(body "$LIST")
check      "list header content-type"      'Content-Type: application/json; charset=utf-8' "$LIST"
check_not  "list header has no Content-Length" 'Content-Length' "$LIST"
check      "list ok:true"                  '"ok":true'          "$LBODY"
check      "list plugin id"                '"plugin":"plugin_docker"' "$LBODY"
check      "list slug docker"              '"slug":"docker"'    "$LBODY"
check      "list version"                  '"version":"1.1.3"'  "$LBODY"
check      "list runtime available"        '"available":true'   "$LBODY"
check      "list daemon available"         '"daemon_available":true' "$LBODY"
check      "list count 3"                  '"count":3'          "$LBODY"
check      "summary total 3"               '"total":3'          "$LBODY"
check      "summary running 2"             '"running":2'        "$LBODY"
check      "summary exited 1"              '"exited":1'         "$LBODY"
check      "container web present"         '"name":"web"'       "$LBODY"
check      "container db present"          '"name":"db"'        "$LBODY"
check      "container old-job present"     '"name":"old-job"'   "$LBODY"
check      "image field present"           '"image":"nginx:1.27"' "$LBODY"
check      "state running present"         '"state":"running"'  "$LBODY"
check      "state exited present"          '"state":"exited"'   "$LBODY"
check      "ports field present"           '0.0.0.0:8080->80/tcp' "$LBODY"
check      "cpu stat merged"               '"cpu":"1.25%"'      "$LBODY"
check      "mem stat merged"               '12.5MiB / 1GiB'     "$LBODY"
printf '%s' "$LBODY" | python3 -c 'import json,sys; d=json.load(sys.stdin); assert len(d["containers"])==3' 2>/dev/null \
    && pass "list body is valid JSON with 3 containers" || fail "list body JSON invalid"

section "mode 2 JSON 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 runtime label"            '"label":"custom"'   "$IBODY"
check      "info pid present"              '"pid":'             "$IBODY"
check      "info utc present"              '"utc":"20'          "$IBODY"
check      "info supported list"           '"supported":["list","info","logs","control"]' "$IBODY"
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"

section "mode 2 JSON logs"
LOGS=$(QUERY_STRING='action=logs&cid=web' "$BIN")
LOG_BODY=$(body "$LOGS")
check      "logs ok:true"                  '"ok":true'          "$LOG_BODY"
check      "logs cid echoed"               '"cid":"web"'        "$LOG_BODY"
check      "logs tail 100"                 '"tail":100'         "$LOG_BODY"
check      "logs exit_code 0"              '"exit_code":0'      "$LOG_BODY"
check      "logs first line"               'line one'           "$LOG_BODY"
check      "logs escapes quotes"           'line two with \"quotes\"' "$LOG_BODY"
check_not  "logs has no Content-Length"    'Content-Length'     "$LOGS"
printf '%s' "$LOG_BODY" | python3 -c 'import json,sys; d=json.load(sys.stdin); assert d["lines"][0]=="line one"' 2>/dev/null \
    && pass "logs body is valid JSON with parsed lines" || fail "logs body JSON invalid"

section "mode 2 unknown action"
UNK=$(QUERY_STRING='action=bogus' "$BIN")
check      "unknown action rejected"       'unknown_action'     "$(body "$UNK")"
check      "unknown action lists supported" '"supported":["list","info","logs","control"]' "$(body "$UNK")"

section "mode 2 no runtime"
LIST2=$(DOCKER_BIN= PATH=/nonexistent QUERY_STRING='action=list' "$BIN")
NRT=$(body "$LIST2")
check      "no-runtime available false"    '"available":false'  "$NRT"
check      "no-runtime graceful message"   'Neither docker nor podman' "$NRT"
check      "no-runtime count 0"            '"count":0'          "$NRT"
LOGS2=$(DOCKER_BIN= PATH=/nonexistent QUERY_STRING='action=logs&cid=web' "$BIN")
check      "no-runtime logs explains why"  'runtime_available' "$(body "$LOGS2")"

section "podman state normalisation"
PODMOCK="$MOCKDIR/podmock"
cat > "$PODMOCK" <<'PODEOF'
#!/bin/sh
case "$1" in
  ps)
    echo "8890ba09c621|registry|registry:2|Up 4 months ago|Up 4 months ago|"
    echo "aa11bb22cc33|job|alpine:3.20|Exited (1) 2 days ago|Exited (1) 2 days ago|"
    echo "dd44ee55ff66|paused-one|redis:7|Paused|Paused|"
    exit 0 ;;
  stats) exit 0 ;;
  *) exit 0 ;;
esac
PODEOF
chmod +x "$PODMOCK"
POD=$(DOCKER_BIN="$PODMOCK" QUERY_STRING='action=list' "$BIN")
PBODY=$(body "$POD")
check "podman: Up becomes running"     '"state":"running"'  "$PBODY"
check "podman: Exited becomes exited"  '"state":"exited"'   "$PBODY"
check "podman: Paused becomes paused"  '"state":"paused"'   "$PBODY"
check "podman: running counted"        '"running":1'        "$PBODY"
check "podman: exited counted"         '"exited":1'         "$PBODY"
check "podman: paused counted"         '"paused":1'         "$PBODY"
check_not "podman: raw status not used as state" '"state":"Up 4 months ago"' "$PBODY"

section "injection & validation"
section "injection & validation"
INJ1=$(QUERY_STRING='action=logs&cid=a;id' "$BIN")
check      "semicolon cid rejected"        'invalid_cid'        "$(body "$INJ1")"
INJ2=$(QUERY_STRING='action=logs&cid=--help' "$BIN")
check      "leading-dash cid rejected"     'invalid_cid'        "$(body "$INJ2")"
INJ3=$(QUERY_STRING='action=logs&cid=a%24(id)' "$BIN")
check      "command-substitution cid rejected" 'invalid_cid'    "$(body "$INJ3")"
INJ4=$(QUERY_STRING='action=logs&cid=8a7b6c5d4e3f' "$BIN")
check      "valid hex cid accepted"        '"ok":true'          "$(body "$INJ4")"
INJ5=$(QUERY_STRING='action=logs&cid=my_app.v2-x' "$BIN")
check      "valid dotted/dashed cid accepted" '"ok":true'      "$(body "$INJ5")"
INJ6=$(QUERY_STRING="action=logs&cid=$(printf 'a%.0s' $(seq 1 200))" "$BIN")
check      "over-long cid rejected"        'invalid_cid'        "$(body "$INJ6")"

section "control (POST-only, op allowlist)"
CG=$(QUERY_STRING='action=control&op=start&cid=web' "$BIN")
check      "control GET refused"           'control_requires_post' "$(body "$CG")"
check      "control GET status 405"        'Status: 405'        "$CG"
CP=$(REQUEST_METHOD=POST CONTENT_LENGTH=17 QUERY_STRING='action=control' \
     sh -c 'printf "op=start&cid=web" | ./plugin_docker')
check      "control POST start ok"         '"ok":true'          "$(body "$CP")"
check      "control POST op echoed"        '"op":"start"'       "$(body "$CP")"
CP2=$(REQUEST_METHOD=POST CONTENT_LENGTH=17 QUERY_STRING='action=control' \
      sh -c 'printf "op=pwn&cid=web  " | ./plugin_docker')
check      "invalid op rejected"           'invalid_op'         "$(body "$CP2")"
CP3=$(REQUEST_METHOD=POST CONTENT_LENGTH=22 QUERY_STRING='action=control' \
      sh -c 'printf "op=stop&cid=a;id      " | ./plugin_docker')
check      "control POST injection rejected" 'invalid_cid'      "$(body "$CP3")"
CP4=$(printf 'op=start&cid=web' | DOCKER_BIN= PATH=/nonexistent \
      REQUEST_METHOD=POST CONTENT_LENGTH=16 QUERY_STRING='action=control' ./plugin_docker)
check      "control POST without runtime degrades" 'runtime_available' "$(body "$CP4")"

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 docker"             '<title>docker</title>' "$HTML"
check      "html back-link present"        'Back to Bot'        "$HTML"
check      "html KPI total"                "k-total"            "$HTML"
check      "html KPI running"              "k-run"              "$HTML"
check      "html table rows host"          "id='rows'"          "$HTML"
check      "html log viewer card"          "logCard"            "$HTML"
check      "html uses /plugins?plugin= route" "/plugins?plugin=" "$HTML"
check      "html uses POST for control"    "method:'POST'"      "$HTML"
check      "html has theme switch"         "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 0d0d10"     '0d0d10'                       "$HTML"
check_not  "html no private palette 16161a"     '16161a'                       "$HTML"
check_not  "html no private palette f4f4f7"     'f4f4f7'                       "$HTML"
THEMEQ=$(QUERY_STRING='theme=light' "$BIN")
check      "?theme=light still renders the UI"  'prefers-color-scheme'     "$THEMEQ"
# ---- end theme handoff ----

check      "html closes document"          '</html>'            "$HTML"
EMB=$(QUERY_STRING='embed=1' "$BIN")
check_not  "embed=1 strips the back-link"  'Back to Bot'        "$EMB"
check      "embed=1 still renders UI"      "k-total"            "$EMB"
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"

section "format=json alias"
FJ=$(QUERY_STRING='format=json' "$BIN")
check      "format=json routes to JSON"    'Content-Type: application/json' "$FJ"

# ---------------------------------------------------------------- optional targets
section "optional cross builds"
if [ -f plugin_docker.musl ]; then
    M=$(./plugin_docker.musl --meta)
    check  "musl build --meta"             '"name":"docker"'    "$M"
else
    echo "  skip musl (not built)"
fi
if [ -f plugin_docker.arm64 ]; then
    case $(head -c 4 plugin_docker.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_docker.arm64 | tr -d ' \n')
    [ "$EM" = "b700" ] && pass "arm64 artifact declares EM_AARCH64" \
        || fail "arm64 artifact e_machine is $EM, expected b700"
elif command -v aarch64-linux-musl-gcc >/dev/null 2>&1 || command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
    A64=$(command -v aarch64-linux-musl-gcc 2>/dev/null || command -v aarch64-linux-gnu-gcc)
    if "$A64" -O2 -std=c99 -static -o /tmp/plugin_docker_arm64_test src/plugin_docker.c 2>/dev/null; then
        pass "aarch64 cross build succeeds"
        EM=$(od -An -tx1 -j 18 -N 2 /tmp/plugin_docker_arm64_test | tr -d ' \n')
        [ "$EM" = "b700" ] && pass "cross-built arm64 declares EM_AARCH64" \
            || fail "cross-built arm64 e_machine is $EM, expected b700"
        rm -f /tmp/plugin_docker_arm64_test
    else
        fail "aarch64 cross build failed"
    fi
else
    echo "  skip arm64 (no aarch64 cross compiler)"
fi
for slice in arm64 x86_64; do
    f="plugin_docker.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
if [ -f plugin_docker.exe ]; then
    MAGIC=$(head -c 2 plugin_docker.exe)
    [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ"
else
    echo "  skip windows PE (not built)"
fi

[ -f plugin.json ] && pass "file present: plugin.json" || fail "file missing: plugin.json"
if [ -f plugin.json ]; then
    python3 - <<'PY' >/dev/null 2>&1 && pass "plugin.json is valid JSON with the contract keys" || fail "plugin.json invalid or missing contract keys"
import json
d = json.load(open("plugin.json"))
for k in ("slug", "id", "title", "summary", "category", "license", "capabilities", "trust_notice"):
    assert k in d, k
assert d["slug"] == "docker" and d["id"] == "plugin_docker", d
assert isinstance(d["capabilities"], list) and d["capabilities"], d
PY
fi

# ---------------------------------------------------------------- history audit
section "git history secret & LAN audit"
if git rev-parse --git-dir >/dev/null 2>&1; then
    ALL="$MOCKDIR/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 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "html has no internal fleet' \
      > "$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}/"
else
    echo "  skip history audit (not a git checkout)"
fi

# ---------------------------------------------------------------- summary
rm -rf "$MOCKDIR"
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
