#!/bin/bash

# Exit if there's no assigned IP address
[ -z "$new_ip_address" ] && exit 0

# Proceed only on lease assignment or recovery
[ "$reason" != "BOUND" ] && [ "$reason" != "REBOOT" ] && exit 0

# Only process Ethernet interfaces like eth0, eth1, etc.
case "$interface" in
    eth*) ;;
    *) exit 0 ;;
esac

# eth0 special
if [ "$interface" = "eth0" ]; then
    echo "Setting default route via eth0"
    ip route replace default via "$new_routers" dev "$interface" src "$new_ip_address"
    exit 0
fi

# Get numeric suffix from interface name for routing table ID
suffix="${interface##eth}"
table_id=$((100 + suffix))
table_name="$interface"

# If this table name isn't in the system yet, register it
if ! grep -q -w "$table_name" /etc/iproute2/rt_tables; then
    echo "Registering route table: $table_name ($table_id)"
    echo "$table_id    $table_name" >> /etc/iproute2/rt_tables
fi

# Calculate CIDR-style subnet using netmask and base network
prefix=$(ipcalc "$new_network_number" "$new_subnet_mask" | awk '/Netmask:/ {print $4}' | cut -d'/' -f2)
subnet_cidr="$new_network_number/$prefix"

# Remove any previous routes or rules for this interface
echo "Flushing table $table_name ($table_id)"
ip route flush table "$table_name"
ip rule del from "$new_ip_address" table "$table_name" 2>/dev/null

# Add subnet route and default gateway to the interface's routing table
echo "Adding routes to table $table_name"
ip route add "$subnet_cidr" dev "$interface" src "$new_ip_address" table "$table_name"
ip route add default via "$new_routers" dev "$interface" table "$table_name"

# Create policy rule so traffic from this IP uses the proper table
echo "Adding ip rule for $new_ip_address"
ip rule add from "$new_ip_address" table "$table_name"

exit 0
