#!/bin/bash

set -e  # Exit immediately if a command fails

# QEMU passes the TAP interface name as $1
TAP_IFACE="$1"

# Debugging: Uncomment to log outputs for debugging
# exec > /tmp/network-up.log 2>&1
# echo "Starting network-up.sh with interface: $TAP_IFACE"

# Check if interface name was provided
if [ -z "$TAP_IFACE" ]; then
    echo "Error: No interface name provided" >&2
    exit 1
fi

# Bring up TAP interface
echo "Bringing up $TAP_IFACE..."
ip link set dev "$TAP_IFACE" up || { echo "Failed to bring up $TAP_IFACE" >&2; exit 1; }

# Check if bridge exists, create if not
if ! ip link show br0 &>/dev/null; then
    echo "Creating bridge br0..."
    ip link add name br0 type bridge || { echo "Failed to create bridge br0" >&2; exit 1; }
fi

# Add TAP device to bridge
echo "Adding $TAP_IFACE to bridge br0..."
ip link set "$TAP_IFACE" master br0 || { echo "Failed to add $TAP_IFACE to br0" >&2; exit 1; }

# Check and assign an IP address to the bridge if not assigned
if ! ip addr show dev br0 | grep -q '192.168.2.15'; then
    echo "Assigning IP 192.168.2.15/24 to br0..."
    ip addr add 192.168.2.15/24 dev br0 || { echo "Failed to assign IP to br0" >&2; exit 1; }
fi

# Bring up the bridge
echo "Bringing up bridge br0..."
ip link set br0 up || { echo "Failed to bring up br0" >&2; exit 1; }

# Enable IP forwarding (optional but often needed)
echo 1 > /proc/sys/net/ipv4/ip_forward

# Add NAT if the host has internet and you want the VM to access it
# Uncomment if needed:
# iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# iptables -A FORWARD -i br0 -o eth0 -j ACCEPT
# iptables -A FORWARD -i eth0 -o br0 -m state --state RELATED,ESTABLISHED -j ACCEPT

echo "Network setup completed successfully for $TAP_IFACE"
exit 0
