#!/bin/bash
# Smoke iterativo end-to-end de las 12 capabilities nuevas (+ 2 base = 14 total).
# Asume device_agent corriendo en 10.42.0.10:7474 con manifest enriched.

set -uo pipefail

URL=http://10.42.0.10:7474/capability
AUDIT_DB=/tmp/device_audit.db
PASS=0
FAIL=0
FAIL_NAMES=()

audit_count_before=$(sqlite3 "$AUDIT_DB" "SELECT COUNT(*) FROM audit_log;" 2>/dev/null || echo 0)
echo "[smoke] audit_log rows BEFORE: $audit_count_before"
echo

call() {
    local name="$1"
    local payload="$2"
    local rid="smoke-$(date +%s%N)-$RANDOM"
    local body
    body=$(echo "$payload" | sed "s/__RID__/$rid/")
    local resp
    resp=$(curl -sS -X POST "$URL" -H "Content-Type: application/json" -d "$body")
    local ok
    ok=$(echo "$resp" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d.get("ok",False))' 2>/dev/null || echo "False")
    if [[ "$ok" == "True" ]]; then
        echo "[OK]  $name"
        PASS=$((PASS+1))
    else
        echo "[FAIL] $name -> $resp"
        FAIL=$((FAIL+1))
        FAIL_NAMES+=("$name")
    fi
}

# 1. shell.exec (baseline)
call "shell.exec" '{"request_id":"__RID__","capability":"shell.exec","args":["echo","smoke-test"]}'

# 2. shell.eval (baseline)
call "shell.eval" '{"request_id":"__RID__","capability":"shell.eval","args":{"cmd":"echo hello-eval"}}'

# 3. fs.read
echo "smoke-payload" > /tmp/smoke_test_file.txt
call "fs.read" '{"request_id":"__RID__","capability":"fs.read","args":{"path":"/tmp/smoke_test_file.txt"}}'

# 4. fs.write
B64=$(echo -n "smoke-write" | base64)
call "fs.write" "{\"request_id\":\"__RID__\",\"capability\":\"fs.write\",\"args\":{\"path\":\"/tmp/smoke_written.txt\",\"content_b64\":\"$B64\"}}"

# 5. fs.list
call "fs.list" '{"request_id":"__RID__","capability":"fs.list","args":{"dir":"/tmp"}}'

# 6. fs.stat
call "fs.stat" '{"request_id":"__RID__","capability":"fs.stat","args":{"path":"/tmp/smoke_test_file.txt"}}'

# 7. git.clone (local repo for offline-safe test)
rm -rf /tmp/smoke_git_src /tmp/smoke_git_dst
mkdir -p /tmp/smoke_git_src && cd /tmp/smoke_git_src && git init -q -b master && git config user.email t@x && git config user.name t && echo seed > f.txt && git add . && git commit -q -m init
call "git.clone" '{"request_id":"__RID__","capability":"git.clone","args":{"url":"/tmp/smoke_git_src","dest":"/tmp/smoke_git_dst"}}'

# 8. git.commit (on cloned repo, add new file)
cd /tmp/smoke_git_dst && git config user.email t@x && git config user.name t && echo new > new.txt
call "git.commit" '{"request_id":"__RID__","capability":"git.commit","args":{"repo":"/tmp/smoke_git_dst","message":"smoke commit","files":["new.txt"]}}'

# 9. git.push: setup bare repo as remote so push succeeds end-to-end
rm -rf /tmp/smoke_git_remote.git
mkdir -p /tmp/smoke_git_remote.git && (cd /tmp/smoke_git_remote.git && git init -q --bare)
(cd /tmp/smoke_git_dst && git remote remove origin 2>/dev/null; git remote add origin /tmp/smoke_git_remote.git)
call "git.push" '{"request_id":"__RID__","capability":"git.push","args":{"repo":"/tmp/smoke_git_dst","remote":"origin","branch":"master"}}'

# 10. pkg.search (use real apt-cache since on ubuntu)
call "pkg.search" '{"request_id":"__RID__","capability":"pkg.search","args":{"query":"vim"}}'

# 11. proc.list
call "proc.list" '{"request_id":"__RID__","capability":"proc.list","args":{}}'

# 12. docker.container.list
call "docker.container.list" '{"request_id":"__RID__","capability":"docker.container.list","args":{"all":true}}'

# 13. docker.container.exec (needs a running container)
CID=$(docker ps --format '{{.Names}}' 2>/dev/null | head -n1)
if [[ -n "$CID" ]]; then
    call "docker.container.exec" "{\"request_id\":\"__RID__\",\"capability\":\"docker.container.exec\",\"args\":{\"container\":\"$CID\",\"argv\":[\"ls\",\"/\"]}}"
else
    echo "[skip docker.container.exec: no running containers]"
fi

# 14. docker.container.logs
if [[ -n "$CID" ]]; then
    call "docker.container.logs" "{\"request_id\":\"__RID__\",\"capability\":\"docker.container.logs\",\"args\":{\"container\":\"$CID\",\"tail\":10}}"
else
    echo "[skip docker.container.logs: no running containers]"
fi

echo
echo "===== SMOKE SUMMARY ====="
echo "PASS: $PASS"
echo "FAIL: $FAIL"
if [[ $FAIL -gt 0 ]]; then
    echo "Failed: ${FAIL_NAMES[*]}"
fi

audit_count_after=$(sqlite3 "$AUDIT_DB" "SELECT COUNT(*) FROM audit_log;" 2>/dev/null || echo 0)
echo "[smoke] audit_log rows AFTER:  $audit_count_after"
echo "[smoke] delta:                 $((audit_count_after - audit_count_before))"
