#!/bin/sh
# tests/run.sh - offline checks for plugin_gitstat across all 3 modes.
#
# Everything runs against ./plugin_gitstat (native build). The repository trees
# are real git repos built in a temp directory, so the status parser, the
# ahead/behind counter, the stash counter, the detached and unborn states and
# the credential redaction are all exercised against git's own output rather
# than our idea of it. GITSTAT_ONLY_ROOTS=1 pins the allowed roots to that temp
# directory so a developer machine full of checkouts cannot affect the result.
#
# Optional cross-target artifacts (musl, aarch64, PE) are checked when present.
# The last section audits the whole git history for secrets and LAN addresses.
#
# Exit code 0 = everything passed.

set -u

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

BIN=./plugin_gitstat
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 500)"
    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 on d]
    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 500)"
    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_gitstat.c || { echo "  build failed"; exit 1; }
fi
[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"

WORK=$(mktemp -d "${TMPDIR:-/tmp}/gitstat-tests-XXXXXX") || exit 1
trap 'rm -rf "$WORK"' EXIT

GIT_AUTHOR_NAME="Gitstat Test"; export GIT_AUTHOR_NAME
GIT_AUTHOR_EMAIL="gitstat@example.invalid"; export GIT_AUTHOR_EMAIL
GIT_COMMITTER_NAME="Gitstat Test"; export GIT_COMMITTER_NAME
GIT_COMMITTER_EMAIL="gitstat@example.invalid"; export GIT_COMMITTER_EMAIL
GIT_CONFIG_GLOBAL=/dev/null; export GIT_CONFIG_GLOBAL
GIT_CONFIG_NOSYSTEM=1; export GIT_CONFIG_NOSYSTEM
GIT_TERMINAL_PROMPT=0; export GIT_TERMINAL_PROMPT

ROOTS="$WORK/roots"
mkdir -p "$ROOTS"

mkrepo() { # mkrepo <dir> <branch>
    mkdir -p "$1"
    git -C "$1" init -q -b "$2"
    git -C "$1" config user.name "Gitstat Test"
    git -C "$1" config user.email "gitstat@example.invalid"
}

# A bare upstream with one commit in it, cloned into <dir>. Using a real clone
# rather than init+remote means the upstream refs actually exist, which is what
# the ahead/behind counters read.
mkclone() { # mkclone <dir> <branch>
    up="$WORK/up-$(basename "$1").git"
    seed="$WORK/seed-$(basename "$1")"
    git init -q --bare "$up"
    git -C "$up" symbolic-ref HEAD "refs/heads/$2"
    mkrepo "$seed" "$2"
    printf 'base\n' > "$seed/base.txt"
    git -C "$seed" add base.txt
    git -C "$seed" commit -q -m "base commit"
    git -C "$seed" remote add origin "$up"
    git -C "$seed" push -q -u origin "$2"
    git clone -q "$up" "$1"
    git -C "$1" config user.name "Gitstat Test"
    git -C "$1" config user.email "gitstat@example.invalid"
}

# 1. clean repo with an upstream, fully in sync
mkclone "$ROOTS/cleanrepo" main

# 2. dirty repo: one modified file, one untracked file, one staged file
mkrepo "$ROOTS/dirtyrepo" main
printf 'one\n' > "$ROOTS/dirtyrepo/keep.txt"
printf 'two\n' > "$ROOTS/dirtyrepo/mod.txt"
printf 'three\n' > "$ROOTS/dirtyrepo/add.txt"
git -C "$ROOTS/dirtyrepo" add keep.txt mod.txt add.txt
git -C "$ROOTS/dirtyrepo" commit -q -m "seed three files"
printf 'modified\n' >> "$ROOTS/dirtyrepo/mod.txt"
printf 'staged\n' >> "$ROOTS/dirtyrepo/add.txt"
git -C "$ROOTS/dirtyrepo" add add.txt
printf 'untracked\n' > "$ROOTS/dirtyrepo/new.txt"

# 3. ahead repo: two local commits past its upstream, plus a stash
mkclone "$ROOTS/aheadrepo" main
printf 'a\n' >> "$ROOTS/aheadrepo/base.txt"
git -C "$ROOTS/aheadrepo" commit -q -am "local commit one"
printf 'b\n' >> "$ROOTS/aheadrepo/base.txt"
git -C "$ROOTS/aheadrepo" commit -q -am "local commit two"
printf 'stashed\n' >> "$ROOTS/aheadrepo/base.txt"
git -C "$ROOTS/aheadrepo" stash push -q -m "work in progress"

# 3b. behind repo: its upstream has moved on
mkclone "$ROOTS/behindrepo" main
other="$WORK/other-behindrepo"
git clone -q "$WORK/up-behindrepo.git" "$other"
git -C "$other" config user.name "Gitstat Test"
git -C "$other" config user.email "gitstat@example.invalid"
printf 'upstream\n' >> "$other/base.txt"
git -C "$other" commit -q -am "upstream moved on"
git -C "$other" push -q origin main
git -C "$ROOTS/behindrepo" fetch -q origin

# 4. detached repo
mkrepo "$ROOTS/detachedrepo" main
printf 'd\n' > "$ROOTS/detachedrepo/d.txt"
git -C "$ROOTS/detachedrepo" add d.txt
git -C "$ROOTS/detachedrepo" commit -q -m "detach me"
printf 'd2\n' >> "$ROOTS/detachedrepo/d.txt"
git -C "$ROOTS/detachedrepo" commit -q -am "second commit"
git -C "$ROOTS/detachedrepo" checkout -q HEAD~1

# 5. unborn repo: initialised, nothing committed
mkrepo "$ROOTS/unbornrepo" main

# 6. repo whose origin URL carries userinfo (must be redacted)
mkclone "$ROOTS/secretremote" main
git -C "$ROOTS/secretremote" remote set-url origin \
    "https://plantuser:planttoken123@example.invalid/x.git"

# 7. a nested repo two levels deep, to prove the walk descends
mkdir -p "$ROOTS/group/nested"
mkrepo "$ROOTS/group/nested/deeprepo" main
printf 'n\n' > "$ROOTS/group/nested/deeprepo/n.txt"
git -C "$ROOTS/group/nested/deeprepo" add n.txt
git -C "$ROOTS/group/nested/deeprepo" commit -q -m "nested seed"

# 8. a directory with no .git at all (must be ignored)
mkdir -p "$ROOTS/notarepo"

ROOTENV="GITSTAT_ONLY_ROOTS=1"
ROOTVAR="GITSTAT_ROOTS=$ROOTS"

# ---------------------------------------------------------------- --meta
section "--meta / discovery"
META=$($BIN --meta)
check "--meta prints name git" '"name":"git"' "$META"
check "--meta prints desc Repo status" '"desc":"Repo status"' "$META"
json_ok "--meta is valid JSON with exactly 2 keys" "$META" "sorted(d.keys())==['desc','name']"
SXMETA=$(env SX_PLUGIN_META=1 $BIN)
check "SX_PLUGIN_META=1 returns the metadata" '"name":"git"' "$SXMETA"
METAQ=$(env SX_PLUGIN_META=1 QUERY_STRING="action=repos" $BIN)
check "--meta wins over the query string" '"name":"git"' "$METAQ"
DESCLEN=$(printf '%s' "$META" | python3 -c "import json,sys;print(len(json.load(sys.stdin)['desc']))")
[ "$DESCLEN" -le 15 ] && pass "desc is <= 15 chars ($DESCLEN)" || fail "desc too long ($DESCLEN)"

# ---------------------------------------------------------------- auth
section "node authentication"
UNAUTH=$(env BOT_PASSWORD=testpw QUERY_STRING="action=repos" \
         GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "unauthenticated action=repos is 401" "Status: 401 Unauthorized" "$UNAUTH"
check "401 body carries the error" '"error":"invalid node password"' "$UNAUTH"

OKPW=$(env BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=repos" \
       GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "X-Bot-Password is accepted" '"ok":true' "$OKPW"

OKBR=$(env BOT_PASSWORD=testpw HTTP_AUTHORIZATION="Bearer testpw" QUERY_STRING="action=repos" \
       GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "Authorization: Bearer is accepted" '"ok":true' "$OKBR"

OKQP=$(env BOT_PASSWORD=testpw QUERY_STRING="action=repos&pwd=testpw" \
       GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "?pwd= is accepted" '"ok":true' "$OKQP"

BADPW=$(env BOT_PASSWORD=testpw QUERY_STRING="action=repos&pwd=nope" \
        GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "wrong ?pwd= is 401" "Status: 401 Unauthorized" "$BADPW"

UNAUTHH=$(env BOT_PASSWORD=testpw QUERY_STRING="" \
          GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "unauthenticated HTML page is 401 too" "Status: 401 Unauthorized" "$UNAUTHH"

METAOK=$(env BOT_PASSWORD=testpw SX_PLUGIN_META=1 $BIN)
check "--meta stays unauthenticated so discovery works" '"name":"git"' "$METAOK"

NOAUTH=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "no BOT_PASSWORD means auth is a no-op" '"ok":true' "$NOAUTH"

# ---------------------------------------------------------------- repos
section "?action=repos"
REPOS=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
REPOSB=$(body "$REPOS")
check "repos answers JSON" "Content-Type: application/json" "$REPOS"
json_ok "repos doc is valid" "$REPOSB"
json_ok "repos reports ok" "$REPOSB" "d['ok'] is True"
json_ok "repos has a summary" "$REPOSB" "'summary' in d and 'dirty' in d['summary']"
json_ok "repos has a roots array with per-root counts" "$REPOSB" \
       "len(d['roots'])==1 and d['roots'][0]['count']==8 and d['roots'][0]['exists']"
json_ok "repos found the 8 fixture repos" "$REPOSB" "d['count']==8"
json_ok "the plain directory is not a repo" "$REPOSB" \
       "not any('notarepo' in r['path'] for r in d['repos'])"
json_ok "the nested repo was found at depth 3" "$REPOSB" \
       "any(r['name']=='deeprepo' for r in d['repos'])"
json_ok "the first repo is a dirty one (dirty-first sort)" "$REPOSB" "d['repos'][0]['dirty']>0"
json_ok "every repo has the documented field set" "$REPOSB" \
       "all(set(r)>=set(['path','name','root','branch','upstream','ahead','behind','dirty','untracked','staged','conflicted','stash','detached','no_upstream','unborn','last_commit']) for r in d['repos'])"
json_ok "last_commit has hash/ct/at/subject" "$REPOSB" \
       "all(set(r['last_commit'])>=set(['hash','short','ct','at','subject']) for r in d['repos'])"
json_ok "checked_at is an ISO-Z stamp" "$REPOSB" "d['checked_at'].endswith('Z')"

# per-repo assertions
DIRTY=$(printf '%s' "$REPOSB" | python3 -c "
import json,sys
d=json.load(sys.stdin)
print(json.dumps([r for r in d['repos'] if r['name']=='dirtyrepo'][0]))")
json_ok "dirtyrepo counts 3 changed entries" "$DIRTY" "d['dirty']==3"
json_ok "dirtyrepo counts 1 untracked" "$DIRTY" "d['untracked']==1"
json_ok "dirtyrepo is not detached and has a branch" "$DIRTY" \
       "d['detached'] is False and d['branch']=='main'"

CLEAN=$(printf '%s' "$REPOSB" | python3 -c "
import json,sys
d=json.load(sys.stdin)
print(json.dumps([r for r in d['repos'] if r['name']=='cleanrepo'][0]))")
json_ok "cleanrepo is clean" "$CLEAN" "d['dirty']==0"
json_ok "cleanrepo is in sync with its upstream" "$CLEAN" "d['ahead']==0 and d['behind']==0"
json_ok "cleanrepo has an upstream" "$CLEAN" "d['no_upstream'] is False and d['upstream']"
json_ok "cleanrepo carried its last commit" "$CLEAN" "d['last_commit']['subject']=='base commit'"

AHEAD=$(printf '%s' "$REPOSB" | python3 -c "
import json,sys
d=json.load(sys.stdin)
print(json.dumps([r for r in d['repos'] if r['name']=='aheadrepo'][0]))")
json_ok "aheadrepo is 2 ahead" "$AHEAD" "d['ahead']==2"
json_ok "aheadrepo is not behind" "$AHEAD" "d['behind']==0"
json_ok "aheadrepo counted its stash" "$AHEAD" "d['stash']==1"
json_ok "aheadrepo last subject is the newest commit" "$AHEAD" \
       "d['last_commit']['subject']=='local commit two'"

DET=$(printf '%s' "$REPOSB" | python3 -c "
import json,sys
d=json.load(sys.stdin)
print(json.dumps([r for r in d['repos'] if r['name']=='detachedrepo'][0]))")
json_ok "detachedrepo is flagged detached" "$DET" "d['detached'] is True"
json_ok "detachedrepo branch reads detached" "$DET" "d['branch']=='detached'"

UNB=$(printf '%s' "$REPOSB" | python3 -c "
import json,sys
d=json.load(sys.stdin)
print(json.dumps([r for r in d['repos'] if r['name']=='unbornrepo'][0]))")
json_ok "unbornrepo is flagged unborn" "$UNB" "d['unborn'] is True"
json_ok "unbornrepo has no upstream" "$UNB" "d['no_upstream'] is True"

SEC=$(printf '%s' "$REPOSB" | python3 -c "
import json,sys
d=json.load(sys.stdin)
print(json.dumps([r for r in d['repos'] if r['name']=='secretremote'][0]))")
check_not "credential in the origin URL is redacted (token)" "planttoken123" "$SEC"
check_not "credential in the origin URL is redacted (user)" "plantuser" "$SEC"
SECUREMOTE=$(body "$(env QUERY_STRING="action=repo&path=$ROOTS/secretremote" \
              GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)")
check "the board row does not pay for the origin URL" '"remote": ""' "$SEC"
json_ok "the detail reads the origin URL" "$SECUREMOTE" \
       "d['repo']['remote']=='https://example.invalid/x.git'"
check_not "the detail remote carries no userinfo" "plantuser" "$SECUREMOTE"
check_not "the detail remote carries no token" "planttoken123" "$SECUREMOTE"

check_not "no path outside the root is reported" "$WORK/upstream.git" "$REPOSB"

# summary counters
json_ok "summary counts the dirty repos" "$REPOSB" "d['summary']['dirty']>=1"
json_ok "summary counts the ahead repo" "$REPOSB" "d['summary']['ahead']>=1"
json_ok "summary counts the behind repo" "$REPOSB" "d['summary']['behind']>=1"
BEHIND=$(printf '%s' "$REPOSB" | python3 -c "
import json,sys
d=json.load(sys.stdin)
print(json.dumps([r for r in d['repos'] if r['name']=='behindrepo'][0]))")
json_ok "behindrepo is 1 behind" "$BEHIND" "d['behind']==1"
json_ok "behindrepo is not ahead" "$BEHIND" "d['ahead']==0"
json_ok "behindrepo still has an upstream" "$BEHIND" "d['no_upstream'] is False"
json_ok "summary counts the stashes" "$REPOSB" "d['summary']['stashes']>=1"
json_ok "summary counts the detached repo" "$REPOSB" "d['summary']['detached']==1"

# empty root
EMPTY=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$WORK/nowhere" $BIN)
json_ok "a missing root reports exists:false" "$(body "$EMPTY")" \
       "d['roots'][0]['exists'] is False and d['count']==0"

# per-root budget: two roots are counted independently
mkdir -p "$WORK/r1" "$WORK/r2"
cp -a "$ROOTS/cleanrepo" "$WORK/r1/one"
cp -a "$ROOTS/cleanrepo" "$WORK/r1/two"
cp -a "$ROOTS/cleanrepo" "$WORK/r2/three"
TWOROOT=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 \
          GITSTAT_ROOTS="$WORK/r1:$WORK/r2" $BIN)
json_ok "two roots keep independent counts" "$(body "$TWOROOT")" \
       "len(d['roots'])==2 and d['roots'][0]['count']==2 and d['roots'][1]['count']==1"
json_ok "the global table is that of both roots" "$(body "$TWOROOT")" "d['count']==3"

# a duplicate root listing is de-duplicated, not double counted
DUPR=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 \
       GITSTAT_ROOTS="$WORK/r1:$WORK/r1" $BIN)
json_ok "a repeated root is de-duplicated" "$(body "$DUPR")" \
       "len(d['roots'])==1 and d['count']==2"

# ---------------------------------------------------------------- repo detail
section "?action=repo&path="
RP="env QUERY_STRING=action=repo\&path=$ROOTS/dirtyrepo GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS=$ROOTS"
DETAIL=$(env QUERY_STRING="action=repo&path=$ROOTS/dirtyrepo" \
         GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
DETB=$(body "$DETAIL")
check "repo detail answers JSON" "Content-Type: application/json" "$DETAIL"
json_ok "repo detail is valid" "$DETB"
json_ok "repo detail reports ok" "$DETB" "d['ok'] is True"
json_ok "repo detail has the repo block" "$DETB" "d['repo']['name']=='dirtyrepo'"
json_ok "repo detail lists 3 changed files" "$DETB" "len(d['changed'])==3"
json_ok "repo detail marks the untracked file" "$DETB" \
       "any(c['code']=='??' and c['path']=='new.txt' for c in d['changed'])"
json_ok "repo detail marks the modified file" "$DETB" \
       "any(c['path']=='mod.txt' and c['code'][1]=='M' for c in d['changed'])"
json_ok "repo detail marks the staged file" "$DETB" \
       "any(c['path']=='add.txt' and c['code'][0]=='M' for c in d['changed'])"
json_ok "repo detail has recent commits" "$DETB" "len(d['commits'])>=1"
json_ok "each commit has hash/ct/author/subject" "$DETB" \
       "all(set(c)>=set(['hash','ct','author','subject']) for c in d['commits'])"
json_ok "changed_count is reported" "$DETB" "d['changed_count']==3"
json_ok "a discovered repo keeps its root attribution" "$DETB" "d['repo']['root']!=''"

# a repo the walk deliberately skipped (it lives inside a node_modules tree) is
# still served when asked for by path, and is attributed to its root
mkdir -p "$ROOTS/node_modules"
cp -a "$ROOTS/cleanrepo" "$ROOTS/node_modules/skipped"
UNSEEN=$(body "$(env QUERY_STRING="action=repo&path=$ROOTS/node_modules/skipped" \
         GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)")
json_ok "the walk skips node_modules" "$REPOSB" \
       "not any('node_modules' in r['path'] for r in d['repos'])"
json_ok "an undiscovered repo is read on demand" "$UNSEEN" "d['ok'] is True"
json_ok "a skipped repo is attributed to its root" "$UNSEEN" \
       "d['repo']['root']=='$ROOTS'"

AHEADD=$(env QUERY_STRING="action=repo&path=$ROOTS/aheadrepo" \
         GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
json_ok "detail of a repo with commits lists newest first" "$(body "$AHEADD")" \
       "d['commits'][0]['subject']=='local commit two'"
json_ok "detail caps commits at 20" "$(body "$AHEADD")" "len(d['commits'])<=20"

# path allowlisting
OUTSIDE=$(env QUERY_STRING="action=repo&path=/etc" \
          GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "a path outside every root is 403" "Status: 403 Forbidden" "$OUTSIDE"
check "403 explains why" "not in an allowlisted root" "$OUTSIDE"

DOTDOT=$(env QUERY_STRING="action=repo&path=$ROOTS/../etc" \
         GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "a .. traversal is refused" "Status: 403 Forbidden" "$DOTDOT"

NOTREPO=$(env QUERY_STRING="action=repo&path=$ROOTS/notarepo" \
          GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "a directory without .git is refused" "Status: 403 Forbidden" "$NOTREPO"

EMPTYP=$(env QUERY_STRING="action=repo&path=" \
         GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "a missing path argument is refused" "Status: 403 Forbidden" "$EMPTYP"

# ---------------------------------------------------------------- fetch
section "?action=fetch"
NOFETCH=$(env QUERY_STRING="action=fetch&path=$ROOTS/cleanrepo" REQUEST_METHOD=POST \
          GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "fetch is disabled by default" '"ok":false' "$NOFETCH"
check "fetch says how to enable it" "GITSTAT_ALLOW_FETCH" "$NOFETCH"

GETFETCH=$(env QUERY_STRING="action=fetch&path=$ROOTS/cleanrepo" \
           GITSTAT_ALLOW_FETCH=1 GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "fetch is POST only" "fetch is POST only" "$GETFETCH"

FETCHOUT=$(env QUERY_STRING="action=fetch&path=$ROOTS/cleanrepo" REQUEST_METHOD=POST \
           GITSTAT_ALLOW_FETCH=1 GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
FB=$(body "$FETCHOUT")
json_ok "enabled fetch returns a JSON document" "$FB"
json_ok "enabled fetch of a clean repo succeeds" "$FB" "d['ok'] is True and d['exit']==0"
json_ok "fetch echoes the branch and sync state" "$FB" "'branch' in d and 'ahead' in d"

FETCHBAD=$(env QUERY_STRING="action=fetch&path=/etc" REQUEST_METHOD=POST \
           GITSTAT_ALLOW_FETCH=1 GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "fetch of a path outside the roots is 403" "Status: 403 Forbidden" "$FETCHBAD"

# ---------------------------------------------------------------- other actions
UNKNOWN=$(env QUERY_STRING="action=bogus" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "an unknown action answers an error document" '"error":"unknown action"' "$UNKNOWN"

FMT=$(env QUERY_STRING="format=json" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "format=json is served as JSON" "Content-Type: application/json" "$FMT"
json_ok "format=json returns the repos document" "$(body "$FMT")" "d['action']=='repos'"

# ---------------------------------------------------------------- HTML
section "HTML UI"
HTML=$(env QUERY_STRING="" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "GET answers HTML" "Content-Type: text/html" "$HTML"
check "the page has a doctype" "<!DOCTYPE html>" "$HTML"
check "the page names the product" "SCORPIOX BOT" "$HTML"
check "the page sets the token block" "--bg:#000000" "$HTML"
check "the page carries the light token block" "data-theme=light" "$HTML"
check "the page carries the prepaint script" "sx-theme-request" "$HTML"
check "the page carries the handoff listener" "sx-theme" "$HTML"
check_not "no external script is referenced" "<script src=" "$HTML"
check_not "no CDN is referenced" "cdn." "$HTML"
check_not "no http URL is referenced in the page" "http://" "$HTML"
check "the page has the rows table" 'id="rows"' "$HTML"
check "the page has the filter chips" 'class="chip' "$HTML"
check "the page has the detail drawer" 'id="drawer"' "$HTML"
check "the page has inline SVG icons" "<svg viewBox" "$HTML"
check "the page has a CSP" "Content-Security-Policy" "$HTML"
check "the page declares the theme toggle hidden in embed" "embed-hide" "$HTML"

EMBED=$(env QUERY_STRING="embed=1" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
check "embed=1 still serves the page" "<!DOCTYPE html>" "$EMBED"
check "embed=1 marks the document embedded" "embed" "$EMBED"

# no emoji anywhere in the page
if printf '%s' "$HTML" | python3 -c "
import sys
s=sys.stdin.buffer.read().decode('utf-8','replace')
bad=[c for c in s if ord(c)>0x2100 and not (0x2010<=ord(c)<=0x2027)]
sys.exit(1 if bad else 0)" 2>/dev/null; then
    pass "no emoji in the page"
else
    fail "the page contains emoji or exotic glyphs"
fi

# the hub-vs-direct route branch must be present, got wrong is the classic bug
check "the page branches on ?plugin= for the hub route" \
      "HUB ? '/plugins?plugin='" "$HTML"
check "the page falls back to the direct node route" "'/plugin_gitstat'" "$HTML"

# ---------------------------------------------------------------- cross targets
section "cross-target artifacts"
if [ -f plugin_gitstat.musl ]; then
    file plugin_gitstat.musl | grep -q 'ELF' && pass "the musl build is an ELF" || fail "musl build is not ELF"
    file plugin_gitstat.musl | grep -qi 'static' && pass "the musl build is statically linked" || fail "musl build is dynamic"
else
    echo "  (skip) plugin_gitstat.musl not built here"
fi
if [ -f plugin_gitstat.arm64 ]; then
    file plugin_gitstat.arm64 | grep -Eq 'aarch64' && pass "the arm64 build is aarch64" || fail "arm64 build is not aarch64"
else
    echo "  (skip) plugin_gitstat.arm64 not built here"
fi
if [ -f plugin_gitstat.exe ]; then
    if head -c 2 plugin_gitstat.exe | od -An -c | grep -q 'M   Z'; then
        pass "the Windows build starts with an MZ header"
    else
        fail "the Windows build is not a PE (no MZ header)"
    fi
else
    echo "  (skip) plugin_gitstat.exe not built here"
fi

# ---------------------------------------------------------------- generated UI
section "generated page"
if command -v python3 >/dev/null 2>&1; then
    if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
        pass "src/ui_html.h matches src/ui.html"
    else
        fail "src/ui_html.h is stale - run tools/gen_ui.py"
    fi
else
    echo "  (skip) python3 not available"
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 "|audit\(\)' \
      > "$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
