#!/bin/bash
# Script to fix OVS configuration permissions and manually create br-ex

echo "=== Fixing OVS Configuration ==="

# Check current OVS bridge status
echo "1. Current OVS status:"
sudo ovs-vsctl show

# Check if openvswitch is running
echo -e "\n2. Ensuring Open vSwitch is running..."
sudo systemctl start openvswitch
sudo systemctl status openvswitch | head -n 5

# Manually create br-ex bridge
echo -e "\n3. Creating br-ex bridge manually..."
sudo ovs-vsctl --may-exist add-br br-ex
sudo ovs-vsctl --may-exist add-port br-ex vlan1182
sudo ip link set br-ex up

# Move IP configuration from vlan1182 to br-ex
echo -e "\n4. Moving IP configuration to br-ex..."
# Get current IP from vlan1182
CURRENT_IP=$(ip -4 addr show vlan1182 | grep -oP '(?<=inet\s)\d+(\.\d+){3}/\d+')
if [ -n "$CURRENT_IP" ]; then
    echo "Moving IP $CURRENT_IP from vlan1182 to br-ex"
    sudo ip addr add $CURRENT_IP dev br-ex
    sudo ip addr del $CURRENT_IP dev vlan1182
fi

# Update default route
echo -e "\n5. Updating routes..."
sudo ip route del default via 10.153.11.0 dev vlan1182 2>/dev/null || true
sudo ip route add default via 10.153.11.0 dev br-ex metric 100

# Create NetworkManager connections for OVS
echo -e "\n6. Creating NetworkManager connections..."
# Create br-ex connection
sudo nmcli con add type ovs-bridge con-name br-ex ifname br-ex
sudo nmcli con add type ovs-port con-name ovs-port-br-ex ifname vlan1182 master br-ex
sudo nmcli con add type ethernet con-name ovs-if-phys0 ifname vlan1182 master ovs-port-br-ex

# Set br-ex IP configuration
sudo nmcli con mod br-ex ipv4.addresses 10.153.11.120/24
sudo nmcli con mod br-ex ipv4.gateway 10.153.11.0
sudo nmcli con mod br-ex ipv4.dns "10.153.11.1"
sudo nmcli con mod br-ex ipv4.method manual
sudo nmcli con mod br-ex connection.autoconnect yes

# Activate connections
echo -e "\n7. Activating connections..."
sudo nmcli con up br-ex

# Verify configuration
echo -e "\n8. Verifying configuration..."
sudo ovs-vsctl show
ip addr show br-ex
ip route | grep default

# Wait for CNI configuration
echo -e "\n9. Checking CNI configuration..."
ls -la /etc/kubernetes/cni/net.d/

# Restart ovnkube-node to pick up changes
echo -e "\n10. Restarting ovnkube-node pod..."
OVNKUBE_POD=$(sudo crictl ps | grep ovnkube-node | awk '{print $9}' | head -1)
if [ -n "$OVNKUBE_POD" ]; then
    echo "Found ovnkube-node pod: $OVNKUBE_POD"
    # The pod should recreate CNI config with br-ex available
fi

echo -e "\nDone! Monitor CNI creation with:"
echo "watch -n 2 'ls -la /etc/kubernetes/cni/net.d/'"