#!/bin/sh

# 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

# Process both traditional (eth*) and predictable (en*) interface names
case "$interface" in
    eth*|en*) ;;
    *) exit 0 ;;
esac

# Special handling for primary interface (eth0 or first en* interface)
primary_interfaces="eth0 enp0s3 ens33"
for primary in $primary_interfaces; do
    if [ "$interface" = "$primary" ]; then
        echo "Setting default route via $interface"
        ip route replace default via "$new_routers" dev "$interface" src "$new_ip_address"
        exit 0
    fi
done

# Extract numeric suffix for routing table ID
# For eth0->0, eth1->1, enp0s3->3, ens33->33, etc.



suffix=$(echo "$interface" | sed 's/[^0-9]*//g' | tail -c 3)
[ -z "$suffix" ] && suffix=99  # Default if no number found
table_id=$((100 + suffix))
table_name="$interface"

# Register table if not exists
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 prefix without ipcalc
calculate_cidr() {
    mask=$1
    bits=0
    IFS='.'
    set -- $mask
    
    for octet in $1 $2 $3 $4; do
        case $octet in
            255) bits=$((bits + 8));;
            254) bits=$((bits + 7));;
            252) bits=$((bits + 6));;
            248) bits=$((bits + 5));;
            240) bits=$((bits + 4));;
            224) bits=$((bits + 3));;
            192) bits=$((bits + 2));;
            128) bits=$((bits + 1));;
            0) ;;
            *) echo "Invalid netmask" >&2; return 1;;
        esac
    done
    echo $bits
}

# Get CIDR prefix
prefix=$(calculate_cidr "$new_subnet_mask")
if [ -z "$prefix" ]; then
    echo "Failed to calculate CIDR prefix" >&2
    exit 1
fi
subnet_cidr="$new_network_number/$prefix"

# Remove ALL previous rules for this table
echo "Cleaning all rules for table $table_name ($table_id)"
ip rule show | grep "lookup $table_name" | while read -r priority rule; do
    # Extract the rule specification
    rule_spec=$(echo "$rule" | sed "s/.*from \([^ ]*\).*/from \1/")
    ip rule del $rule_spec table "$table_name" 2>/dev/null
done

# Flush routing table
echo "Flushing table $table_name ($table_id)"
ip route flush table "$table_name" 2>/dev/null

# Add routes to 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
echo "Adding ip rule for $new_ip_address"
ip rule add from "$new_ip_address" table "$table_name"

# Add subnet-based routing rule for incoming traffic
echo "Adding subnet rule for $subnet_cidr"
ip rule add from "$subnet_cidr" table "$table_name"

exit 0