#!/bin/sh

# Interface name, obtained from the NetworkManager hook parameters
if [[ ! "$IFACE" == eth* ]]; then
    echo "The interface $IFACE does not match the expected pattern 'eth*'."
    exit 0
fi

TABLE_ID=$(shuf -i 100-200 -n 1)
RT_TABLES=/etc/iproute2/rt_tables
TABLE_NAME="rt_$IFACE"

# Dynamically obtain the IP address of the interface
IP_ADDR=$(ip -4 addr show "$IFACE" | grep inet | awk '{print $2}')

IP=$(echo $IP_ADDR | cut -d '/' -f 1)
NETWORK=$(ipcalc -nb $IP_ADDR | grep "Network" | awk '{print $2}')

if [[ ! $(cat $RT_TABLES | grep $TABLE_NAME) == "" ]]; then
	ip route flush table $TABLE_NAME
	for prio in $(ip rule show | grep "$TABLE_NAME" | cut -d ':' -f 1); do
    	ip rule del priority $prio
	done
else
	echo "$TABLE_ID $TABLE_NAME" | tee -a $RT_TABLES
fi

ip route add $NETWORK dev $IFACE proto kernel scope link src $IP table $TABLE_NAME
ip rule add from $IP table $TABLE_NAME

if [ $? -eq 0 ]; then
    echo "Static routes for $IFACE hava been set successfully."
else
    echo "Failed to set static routes for $IFACE." >&2
fi