#!/bin/bash

vmid="$1"

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

# Determine interface
if qm status "$vmid" &>/dev/null; then
    # It's a VM
    iface=$(ip -o link | grep "tap${vmid}i" | awk -F: '{print $2}' | head -n1 | tr -d ' ')
elif pct status "$vmid" &>/dev/null; then
    # It's a container
    mac=$(pct config "$vmid" | grep -iE 'hwaddr|net0' | grep -oE '([0-9a-f]{2}:){5}[0-9a-f]{2}' | head -n1)
    iface=""
    for i in /sys/class/net/veth*/address; do
        [[ $(cat "$i") == "$mac" ]] && iface=$(basename "$(dirname "$i")")
    done
else
    echo "VMID $vmid not found as VM or LXC"
    exit 1
fi

if [[ -z "$iface" ]]; then
    echo "Could not determine interface for VMID $vmid"
    exit 1
fi

iface_mac=$(cat "/sys/class/net/${iface}/address")

echo "Monitoring interface: $iface (MAC: $iface_mac)"
echo "Press Ctrl+C to stop."

# Run tcpdump and format output
tcpdump -n -i "$iface" -l '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