#!/bin/bash
# Fleet audit - verify v2.3 agent on all nodes
SSH_KEY="/home/automation/.ssh/automation_key"
SSH="ssh -i $SSH_KEY -p 30222 -o StrictHostKeyChecking=no -o ConnectTimeout=10"

echo "============================================"
echo " Fleet Audit — v2.3 Agent Verification"
echo "============================================"

# Alpha (local)
echo ""
echo "=== ALPHA (local) ==="
echo -n "  agent.py version: "
head -20 /opt/binary/tools/python/s3rv1c3agent.py | grep VERSION
echo -n "  service desc: "
grep Description /etc/systemd/system/s3rv1c3agent.service
echo -n "  service status: "
systemctl is-active s3rv1c3agent
echo -n "  health: "
curl -sf http://127.0.0.1:8366/health | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d.get("version","?"),d.get("node","?"),d.get("status","?"))' 2>/dev/null || echo "FAIL"
echo -n "  PID type: "
ps -p $(systemctl show s3rv1c3agent -p MainPID --value) -o comm= 2>/dev/null || echo "unknown"

# Remote nodes
for entry in "bravo:10.69.69.3" "charlie:10.69.69.4" "delta:10.69.69.5" "echo:10.69.69.6"; do
    IFS=':' read -r name ip <<< "$entry"
    echo ""
    echo "=== ${name^^} ($ip) ==="
    $SSH automation@$ip "
        echo -n '  agent.py version: '
        head -20 /opt/binary/tools/python/s3rv1c3agent.py 2>/dev/null | grep VERSION || echo 'NOT FOUND'
        echo -n '  service desc: '
        grep Description /etc/systemd/system/s3rv1c3agent.service 2>/dev/null || echo 'NO SERVICE FILE'
        echo -n '  service status: '
        systemctl is-active s3rv1c3agent 2>/dev/null || echo 'inactive'
        echo -n '  health: '
        curl -sf http://127.0.0.1:8366/health 2>/dev/null | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d.get(\"version\",\"?\"),d.get(\"node\",\"?\"),d.get(\"status\",\"?\"))' 2>/dev/null || echo 'FAIL'
        echo -n '  PID type: '
        ps -p \$(systemctl show s3rv1c3agent -p MainPID --value) -o comm= 2>/dev/null || echo 'unknown'
        echo -n '  old bash remnants: '
        ls /opt/binary/tools/bash/s3rv1c3agent* 2>/dev/null || echo 'none'
    " 2>/dev/null || echo "  UNREACHABLE"
done

echo ""
echo "============================================"
echo " Audit complete"
echo "============================================"
