#!/bin/bash

# Generate Traffic from All Running Containers
# This refreshes ARP tables in UDM Pro and network devices

set -euo pipefail

GATEWAY="192.168.11.1"
NODES=("r630-01" "r630-02")

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "=========================================="
echo "Generate Traffic from All Containers"
echo "=========================================="
echo ""

TOTAL_CONTAINERS=0
SUCCESS_COUNT=0
FAILED_COUNT=0

for NODE in "${NODES[@]}"; do
    echo -e "${BLUE}Processing node: ${NODE}${NC}"
    
    # Get all running containers
    CONTAINERS=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
      "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
        'pct list | grep running | awk \"{print \\\$1}\"'" 2>&1)
    
    if [ -z "$CONTAINERS" ]; then
        echo "  No running containers found"
        continue
    fi
    
    for VMID in $CONTAINERS; do
        # Get container IP
        IP=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
          "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
            'pct config ${VMID} 2>/dev/null | grep -oE \"ip=192.168.11.[0-9]+/\" | cut -d= -f2 | cut -d/ -f1 | head -1'" 2>&1)
        
        if [ -z "$IP" ]; then
            continue  # Skip containers without IP
        fi
        
        TOTAL_CONTAINERS=$((TOTAL_CONTAINERS + 1))
        
        # Generate traffic
        RESULT=$(ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@192.168.11.10 \
          "ssh -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 root@${NODE} \
            'pct exec ${VMID} -- ping -c 3 -W 1 ${GATEWAY} 2>&1 | tail -1'" 2>&1)
        
        if echo "$RESULT" | grep -q "0% packet loss\|3 received"; then
            echo -e "  ${GREEN}✅ VMID ${VMID} (${IP}): Traffic generated${NC}"
            SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
        else
            echo -e "  ${YELLOW}⚠️  VMID ${VMID} (${IP}): ${RESULT}${NC}"
            FAILED_COUNT=$((FAILED_COUNT + 1))
        fi
    done
done

echo ""
echo "=========================================="
echo "Traffic Generation Complete"
echo "=========================================="
echo ""
echo "Summary:"
echo "  Total containers: ${TOTAL_CONTAINERS}"
echo "  Successful: ${SUCCESS_COUNT}"
echo "  Failed: ${FAILED_COUNT}"
echo ""
echo "UDM Pro should update client list within 30-60 seconds"
echo ""
