#!/bin/sh
# tests/run.sh - the offline proof for plugin_github.
#
# Everything runs against ./plugin_github with the connector state directory
# pointed at a scratch dir and the API base pointed at tests/mockapi.py on
# loopback, so the suite never touches GitHub, never needs a real credential,
# and never depends on the internet.
#
# Sections:
#   --meta     the node's chip contract (1-2 word name, <= 15 char desc,
#              kind mcp / mcp true / daemon false / menus false) and
#              SX_PLUGIN_META=1 agreeing, version matching plugin.json
#   --schema   the tool array parses and carries the five spec tools
#   mcp.py     initialize/ping/tools/list + all five tools over stdio, each
#              request compared against what the mock actually RECEIVED
#              (method, path, query, Bearer header, JSON body), the PR filter,
#              error relays, the single 503/Retry-After retry
#   cgi.py     status/save/test/tools/clear as real CGI: the 401 gate, the
#              0600 config.json, save validation, and that NO response ever
#              contains the token text
#   asan       the whole mcp.py + cgi.py pass again against the ASan/UBSan +
#              _FORTIFY_SOURCE=2 binary (if this host can run ASan)
#   source     no popen/system/exec, no credential literal, no LAN address,
#              and the page loads no external script
#
# `scorpiox-cli-botplugin audit` runs as a separate gate after the first
# commit (it walks git history) - see the README / release checklist.
#
# Exit code 0 = everything passed.

set -u

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

BIN=${BIN:-./plugin_github}
WORK=$(mktemp -d "${TMPDIR:-/tmp}/gh-suite.XXXXXX")
PORTFILE="$WORK/port"
LOG="$WORK/req.jsonl"
CFGDIR="$WORK/cfg"
CGIDIR="$WORK/cgi"
MOCK_PID=""

cleanup() {
    [ -n "$MOCK_PID" ] && kill "$MOCK_PID" 2>/dev/null
    [ "${KEEP_WORK:-0}" = "1" ] || rm -rf "$WORK"
    [ "${KEEP_WORK:-0}" = "1" ] && echo "work dir kept: $WORK"
}
trap cleanup EXIT INT TERM

PASS=0
FAIL=0

section() { printf '\n== %s ==\n' "$1"; }
pass() { PASS=$((PASS + 1)); printf '  ok   %s\n' "$1"; }
fail() { FAIL=$((FAIL + 1)); printf '  FAIL %s\n' "$1"; }

check() { # check <label> <expected-substring> <text|file>
    if [ -f "$3" ]; then set -- "$1" "$2" "$(cat "$3")"; fi
    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 <label> <forbidden-substring> <text|file>
    if [ -f "$3" ]; then set -- "$1" "$2" "$(cat "$3")"; fi
    if printf '%s' "${3:-}" | grep -F -q -- "$2"; then
        fail "$1 (must NOT contain: $2)"
        printf '       got: %s\n' "$(printf '%s' "${3:-}" | head -c 300)"
    else pass "$1"; fi
}
json_ok() { # json_ok <label> <json> [python expr over `d`]
    expr=${3:-True}
    printf '%s' "${2:-}" > "$WORK/j.json"
    if python3 -c "import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if ($expr) else 1)" \
            "$WORK/j.json" 2>/dev/null; then
        pass "$1"
    else
        fail "$1 (invalid JSON or failed assertion)"
        printf '       got: %s\n' "$(printf '%s' "${2:-}" | head -c 300)"
    fi
}

mkdir -p "$CFGDIR" "$CGIDIR"
rm -f "$LOG"

if [ ! -x "$BIN" ]; then
    echo "plugin_github is not built - run make first" >&2
    exit 1
fi

# ------------------------------------------------------------------ mock
python3 tests/mockapi.py --portfile "$PORTFILE" --log "$LOG" 2>"$WORK/mock.err" &
MOCK_PID=$!
i=0
while [ ! -s "$PORTFILE" ] && [ $i -lt 100 ]; do
    i=$((i + 1)); sleep 0.05
done
if [ ! -s "$PORTFILE" ]; then
    echo "the mock server did not start: $(cat "$WORK/mock.err")" >&2
    exit 1
fi
MOCK="http://127.0.0.1:$(cat "$PORTFILE")"

# ---------------------------------------------------------------- --meta
section "--meta / discovery"
META=$("$BIN" --meta)
json_ok "--meta is one line of valid JSON" "$META"
json_ok "name is the short chip label github" "$META" 'd["name"]=="github"'
json_ok "desc is <= 15 chars"              "$META" 'len(d["desc"])<=15'
json_ok "desc is GitHub tools"             "$META" 'd["desc"]=="GitHub tools"'
json_ok "kind is mcp, mcp true, menus false" \
        "$META" 'd["kind"]=="mcp" and d["mcp"] is True and d["menus"] is False'
json_ok "daemon is false (this connector has no always-on bridge)" \
        "$META" 'd["daemon"] is False'
json_ok "verified is mock (an honest tier: the suite drives a mock, not a live account)" \
        "$META" 'd["verified"]=="mock"'
check "SX_PLUGIN_META=1 agrees"            '"name":"github"' "$(SX_PLUGIN_META=1 "$BIN")"
json_ok "--meta version agrees with plugin.json" "$META" \
        'd["version"]==__import__("json").load(open("plugin.json"))["version"]'

# ---------------------------------------------------------------- --schema
section "--schema"
SCHEMA=$("$BIN" --schema)
json_ok "--schema is valid JSON"          "$SCHEMA"
json_ok "--schema carries exactly the five spec tools" "$SCHEMA" \
        'sorted(t["name"] for t in d["tools"])==sorted(["github_get_repo","github_list_issues","github_create_issue","github_get_pull_request","github_search_code"])'
json_ok "every tool has a description and an inputSchema" "$SCHEMA" \
        'all(t.get("description") and t.get("inputSchema") for t in d["tools"])'
json_ok "create_issue requires owner,repo,title" "$SCHEMA" \
        'set(next(t for t in d["tools"] if t["name"]=="github_create_issue")["inputSchema"]["required"])=={"owner","repo","title"}'
json_ok "search_code requires query"       "$SCHEMA" \
        'next(t for t in d["tools"] if t["name"]=="github_search_code")["inputSchema"]["required"]==["query"]'

# ------------------------------------------------------------ mcp (stdio)
section "--mcp + request shapes (tests/mcp.py)"
if BIN="$BIN" PORT="$(cat "$PORTFILE")" LOG="$LOG" CFGDIR="$CFGDIR" \
        python3 tests/mcp.py; then
    pass "tests/mcp.py exited 0"
else
    fail "tests/mcp.py reported failures"
fi

# ----------------------------------------------------------------- cgi
section "CGI control API (tests/cgi.py)"
if BIN="$BIN" PORT="$(cat "$PORTFILE")" CFGDIR="$CGIDIR" \
        python3 tests/cgi.py; then
    pass "tests/cgi.py exited 0"
else
    fail "tests/cgi.py reported failures"
fi

# ------------------------------------------------------- config from disk
section "config resolution"
# an env token beats the stored one; a stored base beats the default.
# NOTE: the config must be written to the SAME dir the binary is pointed at -
# a mismatch here is a test bug that reads as a plugin bug (it did once).
STOREDIR="$WORK/stored"
mkdir -p "$STOREDIR"
printf "{\"api_base\":\"%s\",\"token\":\"STORED-TOKEN-AAA\"}\n" "$MOCK" > "$STOREDIR/config.json"
chmod 600 "$STOREDIR/config.json"
printf '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"github_create_issue","arguments":{"owner":"o","repo":"r","title":"t"}}}\n' > "$WORK/c1.jsonl"
OUT=$(SX_CONNECTOR_DIR="$STOREDIR" "$BIN" --mcp < "$WORK/c1.jsonl")
check "the stored token is used when no env token is set" "#4221" "$OUT"
printf '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"github_search_code","arguments":{"query":"x"}}}\n' > "$WORK/c2.jsonl"
OUT=$(SX_CONNECTOR_DIR="$STOREDIR" GITHUB_TOKEN="GHPAT-MOCK-TOKEN-1" "$BIN" --mcp < "$WORK/c2.jsonl")
check "GITHUB_TOKEN overrides the stored token" "total_count: 137" "$OUT"
OUT=$(SX_CONNECTOR_DIR="$STOREDIR" GITHUB_TOKEN="GHPAT-MOCK-TOKEN-1" \
        GITHUB_API_BASE="$MOCK" "$BIN" --mcp < "$WORK/c2.jsonl")
check "GITHUB_API_BASE overrides the stored base" "total_count: 137" "$OUT"
check_not "the stored token text never appears in a tool reply" "STORED-TOKEN-AAA" "$OUT"

# ------------------------------------------------------------------ asan
section "ASan + UBSan + _FORTIFY_SOURCE=2"
ASAN=./plugin_github-asan
if make asan >/dev/null 2>&1 && [ -x "$ASAN" ]; then
    # prove the host can actually run ASan before trusting a "pass"
    if ASAN_OPTIONS=detect_leaks=0 "$ASAN" --meta >/dev/null 2>&1; then
        if BIN="$ASAN" PORT="$(cat "$PORTFILE")" LOG="$LOG" CFGDIR="$CFGDIR" \
                python3 tests/mcp.py >"$WORK/asan-mcp.log" 2>&1; then
            pass "the whole MCP pass runs clean under ASan/UBSan"
        else
            fail "the MCP pass fails (or reports leaks) under ASan"
            tail -6 "$WORK/asan-mcp.log" 2>/dev/null | sed 's/^/       /'
        fi
        if BIN="$ASAN" PORT="$(cat "$PORTFILE")" CFGDIR="$WORK/cgi-asan" \
                python3 tests/cgi.py >/dev/null; then
            pass "the whole CGI pass runs clean under ASan/UBSan"
        else
            fail "the CGI pass fails under ASan"
        fi
    else
        printf '  SKIP ASan cannot execute on this host (dyld/ASan incompatibility)\n'
    fi
else
    printf '  SKIP no ASan toolchain here (make asan failed)\n'
fi

# ---------------------------------------------------------------- source
section "source hygiene"
check_not "no popen() anywhere"            "popen("      "src/plugin_github.c src/gh_api.c src/gh_config.c"
FOUND=$(grep -l -E "\bpopen\(|\bsystem\(|\bexecve?\(|\bfork\(" src/*.c 2>/dev/null | grep -v sx_ | tr '\n' ' ')
if [ -z "$FOUND" ]; then
    pass "the connector's own sources shell out to nothing (no popen/system/exec/fork)"
else
    fail "shell execution found in: $FOUND"
fi
FOUND=$(grep -rn -E "ghp_[A-Za-z0-9]{20,}|xox[baprs]-|AKIA[0-9A-Z]{16}" \
        src/ tests/ Makefile plugin.json README.md 2>/dev/null | head -3)
if [ -z "$FOUND" ]; then pass "no credential-shaped literal in the tree"; else
    fail "credential-shaped literal: $FOUND"; fi
FOUND=$(grep -rn -E "192\.168\.|\b10\.[0-9]+\.[0-9]+\.[0-9]+|\b172\.(1[6-9]|2[0-9]|3[01])\." \
        src/ tests/ Makefile plugin.json README.md docs/*.md 2>/dev/null | head -3)
if [ -z "$FOUND" ]; then pass "no private LAN address literal anywhere"; else
    fail "LAN address literal: $FOUND"; fi
PAGE=$(SX_CONNECTOR_DIR="$CGIDIR" REQUEST_METHOD=GET QUERY_STRING="" "$BIN")
check_not "the page loads no external script" "<script src=" "$PAGE"
check_not "the page references no CDN"        "cdnjs"        "$PAGE"
check_not "no token text leaks into the page" "STORED-TOKEN-AAA" "$PAGE"
if grep -q '"build_cmd_posix": *"make"' plugin.json; then
    pass "plugin.json declares its own build command (make)"
else
    fail "plugin.json does not declare build_cmd_posix: make"
fi
if grep -q '^win64:' Makefile; then
    pass "make win64 is a real Makefile target"
else
    fail "the Makefile has no win64 target while plugin.json advertises make win64"
fi

# ------------------------------------------------------------------ done
printf '\n== summary ==\n%s passed, %s failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ] || exit 1
exit 0
