# wg_dhcp_exit_hook: Add new ip routing rules, once we have the DHCP assigned
#                    address.
#
# Note: Must be a bash-compatible script

wg_dhcp_new_netaddr() {
    IFS=. read -r i1 i2 i3 i4 <<< "$1"
    IFS=. read -r m1 m2 m3 m4 <<< "$2"
    printf "%d.%d.%d.%d\n" "$((i1&m1))" "$((i2&m2))" "$((i3&m3))" "$((i4&m4))"
}

case "$reason" in
    "BOUND"|"RENEW"|"REBIND"|"REBOOT")
        if [ -n "$interface" ] && grep -q "wg_${interface}" /etc/iproute2/rt_tables ; then
            if [ -n "$new_ip_address" ] && [ -n "$new_subnet_mask" ] ; then
                new_net_address=$(wg_dhcp_new_netaddr "$new_ip_address" "$new_subnet_mask")
                if [ -n "$new_net_address" ] && [ "$new_net_address" != "0.0.0.0" ] ; then
                    # Add routes to the wg_${interface} table
                    /sbin/ip route add $new_net_address/$new_subnet_mask dev ${interface} src ${new_ip_address} table wg_${interface} || true
                    for router in $new_routers; do
                        /sbin/ip route add default via ${router} dev ${interface} table wg_${interface} || true
                    done
                fi
                # Add the lookup rules for the wg_${interface} table
                /sbin/ip rule add from $new_ip_address table wg_${interface} || true
                /sbin/ip rule add to $new_ip_address table wg_${interface} || true
            fi
        fi
    ;;
esac
