# 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() {
    i1=$(echo $1|cut -f1 -d".")
    i2=$(echo $1|cut -f2 -d".")
    i3=$(echo $1|cut -f3 -d".")
    i4=$(echo $1|cut -f4 -d".")
    m1=$(echo $2|cut -f1 -d".")
    m2=$(echo $2|cut -f2 -d".")
    m3=$(echo $2|cut -f3 -d".")
    m4=$(echo $2|cut -f4 -d".")
    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
                priority="priority $(grep wg_${interface} /etc/iproute2/rt_tables | cut -f1)"
                /sbin/ip rule add from $new_ip_address table wg_${interface} ${priority} || true
                /sbin/ip rule add to $new_ip_address table wg_${interface} ${priority} || true
            fi
        fi
    ;;
esac
