#!/bin/bash

vmid="$1"

if [[ -z "$vmid" ]]; then
    echo "Usage: $0 <lxc-vmid>"
    exit 1
fi

# Confirm container exists
if ! pct status "$vmid" &>/dev/null; then
    echo "❌ LXC container $vmid not found"
    exit 1
fi

# Look for all host veth interfaces matching this VMID
interfaces=($(ip -o link | grep -o "veth${vmid}i[0-9]\b"))

if [[ ${#interfaces[@]} -eq 0 ]]; then
    echo "❌ No interfaces found for LXC $vmid"
    exit 1
fi

echo "✅ Found interfaces for LXC $vmid: ${interfaces[*]}"
echo "📡 Starting tcpdump on each. Press Ctrl+C to stop."

for iface in "${interfaces[@]}"; do
    (
        iface_mac=$(cat /sys/class/net/$iface/address 2>/dev/null || echo "unknown-mac")
        tcpdump -n -l -i "$iface" 'ip' 2>/dev/null | while read -r line; do
            if [[ "$line" =~ ^([0-9:.]+)\ IP\ ([0-9.]+)\.([0-9]+)\ \>\ ([0-9.]+)\.([0-9]+) ]]; then
                timestamp="${BASH_REMATCH[1]}"
                src_ip="${BASH_REMATCH[2]}"
                src_port="${BASH_REMATCH[3]}"
                dst_ip="${BASH_REMATCH[4]}"
                dst_port="${BASH_REMATCH[5]}"
                yymmdd=$(date +%y%m%d)
                echo "$yymmdd $timestamp $vmid $iface_mac IP ${src_ip}:${src_port} > ${dst_ip}:${dst_port}"
            fi
        done
    ) &
done

wait
