#!/bin/bash

KUBECONFIG_FILE="/home/ubuntu/.kube/config"


function check_kubectl() {
    if ! command -v kubectl &> /dev/null; then
        echo "kubectl could not be found."
        exit 1
    fi
}

function get_nodes_and_cidrs() {
    kubectl --kubeconfig "$KUBECONFIG_FILE" get nodes \
            -o jsonpath='{range .items[*]}{.metadata.name} {.spec.podCIDR}{"\n"}{end}'
}

function get_node_ip() {
    local node=$1
    kubectl --kubeconfig "$KUBECONFIG_FILE" get node "$node" \
            -o jsonpath='{.status.addresses[?(@.type=="InternalIP")].address}'
}

function add_route() {
    local cidr=$1
    local node_ip=$2

    if ip route show | grep -q "$cidr"; then
      echo "Route for $cidr already exists. Skipping."
    else
      echo "Adding route for CIDR $cidr via node $node_ip"
      sudo ip route add "$cidr" via "$node_ip"
    fi
}

function config_connectivity() {
    
    echo "Configuring connectivity between nodes."

    check_kubectl
    nodes=$(get_nodes_and_cidrs)
    echo "$nodes" | while read -r node cidr; do
        if [[ -z "$cidr" ]]; then
            echo "No CIDR found for node $node. Skipping."
            continue
        fi

        node_ip=$(get_node_ip "$node")

        if [[ -z "$node_ip" ]]; then
            echo "No IP address found for node $node. Skipping."
            continue
        fi

        add_route $cidr $node_ip

    done

    echo "Configuration connectivity completed."
}