#!/bin/bash
# Check Python versions + restart agents on all nodes
SSH_KEY="/home/automation/.ssh/automation_key"
SSH="ssh -i $SSH_KEY -p 30222 -o StrictHostKeyChecking=no -o ConnectTimeout=10"

echo "=== PYTHON VERSIONS ==="
echo -n "alpha (10.69.69.1): "
python3 --version

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 -n "$name ($ip): "
    $SSH automation@$ip "python3 --version" 2>/dev/null || echo "unreachable"
done

echo ""
echo "=== FORCE RESTART V2.3 AGENTS ==="
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 "
        sudo systemctl stop s3rv1c3agent 2>/dev/null
        sudo pkill -f 's3rv1c3agent' 2>/dev/null
        sleep 1
        sudo systemctl daemon-reload
        sudo systemctl start s3rv1c3agent
        sleep 2
        status=\$(sudo systemctl is-active s3rv1c3agent)
        health=\$(curl -sf http://localhost:8366/health 2>/dev/null || curl -sf http://$ip:8366/health 2>/dev/null || echo '{\"status\":\"failed\"}')
        echo \"  service: \$status\"
        echo \"  health: \$health\" | head -1
    " 2>/dev/null || echo "  UNREACHABLE"
done

echo ""
echo "=== FINAL FLEET STATUS ==="
for ip in 10.69.69.1 10.69.69.3 10.69.69.4 10.69.69.5 10.69.69.6; do
    echo -n "$ip: "
    curl -sf "http://$ip:8366/health" 2>/dev/null | python3 -c 'import sys,json; d=json.load(sys.stdin); v=d.get("version","old"); n=d.get("node","?"); s=d.get("status","?"); print("v"+v+" node="+n+" status="+s)' 2>/dev/null || echo "check failed"
done
