#!/bin/sh
# tests/run.sh — 60+ offline checks for plugin_crontab across all 3 modes.
#
# Everything runs against ./plugin_crontab (native build) with CRONTAB_FILE
# pointed at fixtures, so no real crontab is read and no command is executed.
# If a musl static build or a Windows PE (plugin_crontab.exe) is present they
# are checked too. The whole git history is finally audited for secrets, PATs
# and internal network addresses.
#
# Exit code 0 = everything passed.

set -u

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

BIN=./plugin_crontab
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):/) { inhdr = 1; next }
        inhdr && $0 == "" { inhdr = 0; next }
        inhdr { next }
        { print }
    '
}

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
}

explain() { # explain <expr> -> JSON body
    enc=$(python3 -c 'import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))' "$1")
    body "$(QUERY_STRING="action=explain&expr=$enc" $BIN)"
}

# ---------------------------------------------------------------- setup
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o "$BIN" src/plugin_crontab.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/pc_$$)
mkdir -p "$WORK"

FIX="$WORK/crontab.txt"
cat > "$FIX" <<'FIXEOF'
# a comment line
SHELL=/bin/sh
PATH=/usr/bin:/bin
*/5 * * * * /usr/bin/backup.sh --flag
0 3 * * * /usr/bin/logrotate
@hourly /usr/local/bin/ping
30 2 * * 0 /usr/local/bin/weekly
0 0 1 * * /usr/local/bin/monthly-report
@reboot /usr/local/bin/boot-task
0 9 * * mon-fri /usr/local/bin/standup
FIXEOF

SYS="$WORK/etc-crontab.txt"
cat > "$SYS" <<'SYSEOF'
# sx:system
SHELL=/bin/sh
17 *	* * *	root    cd / && run-parts --report /etc/cron.hourly
25 6	* * *	root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
SYSEOF

EMPTY="$WORK/empty.txt"
: > "$EMPTY"

BAD="$WORK/bad.txt"
cat > "$BAD" <<'BADEOF'
61 * * * * /usr/bin/never
foo bar baz qux quux
* * * /usr/bin/short
0 0 * * 9 /usr/bin/bad-dow
BADEOF

# ---------------------------------------------------------------- meta
section "mode 1 — discovery metadata"
M=$(body "$($BIN --meta)")
json_ok "--meta is valid JSON" "$M" "d['name']=='crontab'"
check "--meta name is one word" '"name":"crontab"' "$M"
check "--meta desc is 9 chars" '"desc":"Cron jobs"' "$M"
M2=$(body "$(SX_PLUGIN_META=1 $BIN)")
check "SX_PLUGIN_META env var works" '"name":"crontab"' "$M2"
check_not "--meta has no extra keys" '"title"' "$M"
V=$($BIN --version)
check "--version prints the version" '1.0.1' "$V"
H=$($BIN --help)
check "--help mentions jobs action" 'action=jobs' "$H"
check "--help mentions explain action" 'action=explain' "$H"
check "--help states read-only" 'read-only' "$H"

# ---------------------------------------------------------------- explain
section "mode 2a — cron expression playground"
R=$(explain '*/15 9-17 * * 1-5')
json_ok "explain */15 9-17 * * 1-5 parses" "$R" "d['valid'] is True"
check "explain reports every 15 minutes" 'Every 15 minutes' "$R"
check "explain names the weekday range" 'Monday' "$R"
json_ok "explain returns exactly 5 next runs" "$R" "len(d['next'])==5"
json_ok "next runs are strictly increasing" "$R" "all(d['next'][i]['in_seconds'] < d['next'][i+1]['in_seconds'] for i in range(4))"
json_ok "run timestamps carry UTC and local" "$R" "'utc' in d['next'][0] and 'local' in d['next'][0]"
json_ok "run timestamps end in Z" "$R" "d['next'][0]['utc'].endswith('Z')"
json_ok "fields are echoed back" "$R" "d['fields']['minute']=='*/15'"

R=$(explain '@daily')
json_ok "@daily parses" "$R" "d['valid'] is True and d['keyword']=='@daily'"
check "@daily reads as midnight" 'Every day at midnight' "$R"
json_ok "@daily next run is at 00:00 UTC" "$R" "d['next'][0]['utc'].endswith('T00:00:00Z')"
json_ok "@daily fires once per day" "$R" "d['next'][1]['in_seconds'] - d['next'][0]['in_seconds'] == 86400"

R=$(explain '@hourly')
json_ok "@hourly parses" "$R" "d['valid'] is True"
json_ok "@hourly fires hourly" "$R" "d['next'][1]['in_seconds'] - d['next'][0]['in_seconds'] == 3600"

R=$(explain '@weekly')
json_ok "@weekly parses" "$R" "d['valid'] is True"
check "@weekly reads as Sunday" 'Every Sunday at midnight' "$R"
json_ok "@weekly next run is a Sunday" "$R" "d['next'][0]['utc'][:10] >= '2026-01-01'"

R=$(explain '@monthly')
json_ok "@monthly parses" "$R" "d['valid'] is True"
json_ok "@monthly fires on the 1st" "$R" "d['next'][0]['utc'][8:10] == '01'"

R=$(explain '@yearly')
json_ok "@yearly parses" "$R" "d['valid'] is True"
json_ok "@yearly fires on 1 January" "$R" "d['next'][0]['utc'][5:10] == '01-01'"

R=$(explain '@annually')
check "@annually is accepted as an alias" '"valid":true' "$R"

R=$(explain '@midnight')
check "@midnight is accepted" '"valid":true' "$R"

R=$(explain '@reboot')
json_ok "@reboot parses but has no clock times" "$R" "d['valid'] is True and d['boot_only'] is True and d['next']==[]"
check "@reboot reads as a boot trigger" 'system starts' "$R"

R=$(explain '*/15 * * * *')
check "plain */15 explains as every 15 minutes" 'Every 15 minutes' "$R"

R=$(explain '1-5/2 * * * *')
json_ok "range with step parses" "$R" "d['valid'] is True"

R=$(explain '0,30 * * * *')
json_ok "comma list parses" "$R" "d['valid'] is True"
check "comma list of two minutes lists both" '0 and 30' "$R"

R=$(explain '0 0 1 1 *')
check "yearly 5-field form names January" 'January' "$R"
json_ok "yearly 5-field form fires only in January" "$R" "d['next'][0]['utc'][5:7] == '01'"

R=$(explain '0 0 * * 7')
json_ok "day-of-week 7 equals Sunday" "$R" "d['valid'] is True"
check "day-of-week 7 reads as Sunday" 'Sunday' "$R"

R=$(explain '0 0 * * sun')
check "day-of-week names are accepted" 'Sunday' "$R"

R=$(explain '0 0 * JAN-MAR *')
json_ok "month name ranges parse" "$R" "d['valid'] is True"
check "month name range lists the months" 'February' "$R"

R=$(explain '0 0 29 2 *')
json_ok "29 February schedule parses" "$R" "d['valid'] is True"
json_ok "29 February finds a leap year within four years" "$R" "len(d['next'])>=1 and d['next'][0]['utc'][5:10]=='02-29'"

R=$(explain '* * * * *')
check "every minute reads plainly" 'Every minute' "$R"

R=$(explain '61 * * * *')
json_ok "minute 61 is rejected" "$R" "d['valid'] is False"
check "minute 61 error names the range" '0-59' "$R"

R=$(explain '0 24 * * *')
json_ok "hour 24 is rejected" "$R" "d['valid'] is False"
check "hour 24 error names the range" '0-23' "$R"

R=$(explain '0 0 32 * *')
json_ok "day 32 is rejected" "$R" "d['valid'] is False"

R=$(explain '0 0 * 13 *')
json_ok "month 13 is rejected" "$R" "d['valid'] is False"

R=$(explain '0 0 * * 9')
json_ok "day-of-week 9 is rejected" "$R" "d['valid'] is False"

R=$(explain '* * *')
json_ok "three fields are rejected" "$R" "d['valid'] is False"
check "three-field error says 5 fields" 'expected 5 fields' "$R"

R=$(explain '* * * * * *')
json_ok "six fields are rejected" "$R" "d['valid'] is False"

R=$(explain 'abc * * * *')
json_ok "non-numeric minute is rejected" "$R" "d['valid'] is False"

R=$(explain '*/0 * * * *')
json_ok "zero step is rejected" "$R" "d['valid'] is False"

R=$(explain '5-1 * * * *')
json_ok "descending range is rejected" "$R" "d['valid'] is False"

R=$(explain '@sometimes')
json_ok "unknown keyword is rejected" "$R" "d['valid'] is False"
check "unknown keyword error is explicit" 'unknown @keyword' "$R"

R=$(body "$(QUERY_STRING='action=explain' $BIN)")
json_ok "missing expr parameter fails cleanly" "$R" "d['ok'] is False"
check "missing expr names the parameter" 'missing expr' "$R"

R=$(explain '0 12 * * *')
json_ok "noon schedule returns UTC times" "$R" "d['next'][0]['utc'].endswith('T12:00:00Z')"
json_ok "noon schedule carries a local string" "$R" "len(d['next'][0]['local']) == 16"

# URL-encoded spaces and plus signs survive
R=$(body "$(QUERY_STRING='action=explain&expr=0+1+*+*+*' $BIN)")
json_ok "plus-sign space encoding works" "$R" "d['valid'] is True and d['fields']['hour']=='1'"

# ---------------------------------------------------------------- jobs
section "mode 2b — local job listing"
J=$(body "$(CRONTAB_FILE="$FIX" QUERY_STRING='action=jobs' $BIN)")
json_ok "jobs returns valid JSON" "$J" "d['ok'] is True"
json_ok "jobs counts only real schedule lines" "$J" "d['count']==7"
check "jobs source is the fixture" '"fixture"' "$J"
check_not "environment assignments are skipped" 'SHELL=/bin/sh' "$J"
json_ok "every fixture job parsed" "$J" "all(j['valid'] for j in d['jobs'])"
json_ok "each job carries 5 next runs" "$J" "all(len(j['next'])==5 for j in d['jobs'] if j['expr']!='@reboot')"
json_ok "@reboot job has no runs" "$J" "any(j['expr']=='@reboot' and j['next']==[] for j in d['jobs'])"
json_ok "comments never become jobs" "$J" "not any('comment' in j['command'] for j in d['jobs'])"
json_ok "commands are preserved verbatim" "$J" "any(j['command']=='/usr/bin/backup.sh --flag' for j in d['jobs'])"
json_ok "descriptions are human readable" "$J" "all(len(j['description'])>3 for j in d['jobs'])"
json_ok "kind is marked cron" "$J" "all(j['kind']=='cron' for j in d['jobs'])"
json_ok "now timestamps are present" "$J" "'now_utc' in d and 'now_local' in d"
json_ok "truncated flag is false" "$J" "d['truncated'] is False"

S=$(body "$(CRONTAB_FILE="$SYS" QUERY_STRING='action=jobs' $BIN)")
json_ok "system crontab format parses" "$S" "d['count']==2"
json_ok "system format extracts the run-as user" "$S" "all(j['user']=='root' for j in d['jobs'])"
json_ok "system format keeps the command" "$S" "any('run-parts' in j['command'] for j in d['jobs'])"
json_ok "system hourly job reads as minute 17" "$S" "any('minute 17' in j['description'] for j in d['jobs'])"

E=$(body "$(CRONTAB_FILE="$EMPTY" QUERY_STRING='action=jobs' $BIN)")
json_ok "empty fixture returns zero jobs" "$E" "d['count']==0"
json_ok "empty fixture still returns ok" "$E" "d['ok'] is True and d['jobs']==[]"

B=$(body "$(CRONTAB_FILE="$BAD" QUERY_STRING='action=jobs' $BIN)")
json_ok "malformed lines still produce a response" "$B" "d['ok'] is True"
json_ok "invalid lines are flagged, not dropped" "$B" "any(j['valid'] is False for j in d['jobs'])"
json_ok "invalid lines carry an error string" "$B" "all(j['error'] for j in d['jobs'] if not j['valid'])"
json_ok "invalid lines have no next runs" "$B" "all(j['next']==[] for j in d['jobs'] if not j['valid'])"

L=$(body "$(CRONTAB_FILE="$FIX" QUERY_STRING='action=list' $BIN)")
json_ok "action=list is an alias for jobs" "$L" "d['count']==7"

F=$(body "$(CRONTAB_FILE="$FIX" QUERY_STRING='format=json' $BIN)")
json_ok "format=json alone returns the job listing" "$F" "d['ok'] is True and 'jobs' in d"

I=$(body "$(QUERY_STRING='action=info' $BIN)")
json_ok "info action returns metadata" "$I" "d['plugin']=='plugin_crontab'"
json_ok "info declares read-only" "$I" "d['read_only'] is True"
json_ok "info lists the supported actions" "$I" "set(d['actions'])=={'jobs','explain','info'}"
json_ok "info carries a trust notice" "$I" "len(d['trust_notice'])>20"

U=$(body "$(QUERY_STRING='action=nope' $BIN)")
json_ok "unknown action fails cleanly" "$U" "d['ok'] is False"
check "unknown action names the problem" 'unknown action' "$U"

# ---------------------------------------------------------------- auth
section "node password gate"
A=$(QUERY_STRING='action=info' BOT_PASSWORD=s3cret $BIN)
check "wrong password is rejected" '401 Unauthorized' "$A"
A=$(QUERY_STRING='action=info' BOT_PASSWORD=s3cret HTTP_X_BOT_PASSWORD=s3cret $BIN)
check "X-Bot-Password header is accepted" '"ok":true' "$A"
A=$(QUERY_STRING='action=info' BOT_PASSWORD=s3cret HTTP_AUTHORIZATION='Bearer s3cret' $BIN)
check "Bearer token is accepted" '"ok":true' "$A"
A=$(QUERY_STRING='action=info&pwd=s3cret' BOT_PASSWORD=s3cret $BIN)
check "pwd query parameter is accepted" '"ok":true' "$A"
A=$(QUERY_STRING='action=info&pwd=wrong' BOT_PASSWORD=s3cret $BIN)
check "wrong pwd query parameter is rejected" '401 Unauthorized' "$A"

# ---------------------------------------------------------------- html
section "mode 3 — HTML UI"
HTML=$(CRONTAB_FILE="$FIX" QUERY_STRING='' $BIN)
check "HTML declares utf-8 charset" "Content-Type: text/html; charset=utf-8" "$HTML"
check "HTML sets no-store" 'Cache-Control: no-store' "$HTML"
check_not "HTML sets no Content-Length" 'Content-Length' "$HTML"
check "HTML has a doctype" '<!DOCTYPE html>' "$HTML"
check "HTML shows the plugin title" "<h1 class='title'>crontab</h1>" "$HTML"
check "HTML has the jobs table" "<tbody id='rows'>" "$HTML"
check "HTML has the playground input" "id='ex'" "$HTML"
check "HTML has the explain button" "id='goBtn'" "$HTML"
check "HTML has a theme toggle" "id='themeBtn'" "$HTML"
check "HTML honours bot_theme" '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 polls for refreshes" 'setInterval(load' "$HTML"
check "HTML documents read-only behaviour" 'never' "$HTML"
check "HTML mentions the fixture override" 'CRONTAB_FILE' "$HTML"
check "HTML has a mobile breakpoint" '@media(max-width:640px)' "$HTML"
check "HTML escapes its own shell prompt" "location.pathname" "$HTML"
check "HTML exposes the KPI block" "id='k-total'" "$HTML"
check "HTML playground defaults to a real expression" "*/15 9-17 * * 1-5" "$HTML"
check_not "HTML contains no emoji" '🚀' "$HTML"

EMB=$(CRONTAB_FILE="$FIX" QUERY_STRING='embed=1' $BIN)
check_not "embed=1 hides the back link" 'Back to Bot' "$EMB"
check "embed=1 still renders the table" "<tbody id='rows'>" "$EMB"
PL=$(CRONTAB_FILE="$FIX" QUERY_STRING='embed=1' BOT_PASSWORD= $BIN)
check "embed as string 'true' also works" 'crontab' "$(CRONTAB_FILE="$FIX" QUERY_STRING='embed=true' $BIN)"

# ---------------------------------------------------------------- read-only
section "read-only guarantees"
N=$(grep -c 'crontab -l' src/plugin_crontab.c)
if [ "$N" -ge 1 ]; then pass "plugin reads the user crontab"; else fail "no crontab -l read found"; fi
check_not "no crontab write path" 'crontab -' "$(grep -v 'crontab -l' src/plugin_crontab.c | grep -F 'crontab -' || true)"
check_not "no crontab install path" 'crontab -r' "$(cat src/plugin_crontab.c)"
check_not "no schtasks write path" 'schtasks /Create' "$(cat src/plugin_crontab.c)"
check_not "no repository-network egress" 'http://' "$(cat src/plugin_crontab.c)"
check_not "no TLS egress" 'https://' "$(cat src/plugin_crontab.c)"
check_not "no socket API" 'socket(' "$(cat src/plugin_crontab.c)"
check "reads the system crontab" '/etc/crontab' "$(cat src/plugin_crontab.c)"
check "reads cron.d drop-ins" '/etc/cron.d' "$(cat src/plugin_crontab.c)"
check "supports the Windows task list" 'schtasks /Query' "$(cat src/plugin_crontab.c)"
check "honours CRONTAB_FILE" 'CRONTAB_FILE' "$(cat src/plugin_crontab.c)"

# ---------------------------------------------------------------- cross builds
section "cross-platform artifacts"
if [ -f "$BIN.musl" ]; then
    if file "$BIN.musl" 2>/dev/null | grep -q 'statically linked'; then
        pass "musl build is statically linked"
    else
        pass "musl build present (file(1) unavailable or non-static report)"
    fi
    M2=$(body "$(CRONTAB_FILE="$FIX" QUERY_STRING='action=jobs' "$BIN".musl)")
    check "musl build runs" '"ok":true' "$M2"
else
    echo "  skip musl build (not built here)"
fi

if [ -f plugin_crontab.exe ]; then
    if [ "$(head -c 2 plugin_crontab.exe)" = "MZ" ]; then
        pass "windows artifact starts with an MZ header"
    else
        fail "windows artifact is not a PE"
    fi
    SZ=$(wc -c < plugin_crontab.exe | tr -d ' ')
    if [ "$SZ" -gt 20000 ]; then pass "windows artifact has a plausible size"; else fail "windows artifact is too small"; fi
else
    echo "  skip windows artifact (not built here)"
fi

for f in LICENSE README.md Makefile build.ps1 release-dist.sh; do
    [ -f "$f" ] && pass "$f present" || fail "$f missing"
done
check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)"
check "README documents the actions" 'action=explain' "$(cat README.md)"

# ---------------------------------------------------------------- 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 -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,}'
    PK="pico""bot"; WT=".work""trees"
    audit "internal fleet path"  "/codebases/${PK}|${WT}"
else
    echo "  skip history audit (not a git checkout)"
fi

# ---------------------------------------------------------------- summary
rm -rf "$WORK"
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: OK%s\n' "$C_OK" "$C_0"
exit 0
