#!/bin/bash

# usage example
# config_iptables "10.244.1.0/24"

function config_iptables() {
    local SUBNET="$1"
    local COMMENT="cni-plugin-bash traffic"

    echo "Enabling IP forwarding."
    sudo sysctl -w net.ipv4.ip_forward=1

    echo "Setting up iptables rules."
    if sudo iptables -t filter -S FORWARD | grep -q -F "$COMMENT"; then
        echo "Rule already exists in FORWARD chain."
    else
        echo "Setting FORWARD chain."
        sudo iptables -t filter -A FORWARD -s "$SUBNET" -m comment --comment "$COMMENT" -j ACCEPT
        sudo iptables -t filter -A FORWARD -d "$SUBNET" -m comment --comment "$COMMENT" -j ACCEPT
    fi

    echo "Setting up masquerading."
    if sudo iptables -t nat -S POSTROUTING | grep -q -F "$COMMENT"; then
        echo "Rule already exists in POSTROUTING chain."
    else
        sudo iptables -t nat -A POSTROUTING -s "$SUBNET" -m comment --comment "$COMMENT" -j MASQUERADE
    fi

    echo "Configuration iptables completed."
}
