# Set dhcp.<iface>.routeN.dest and dhcp.<iface>.routeN.via properties with
# the static routes provided by the DHCP server.

# CAUTION
#
# Placing this in the hooks directory will allow DHCP servers to push static
# routes to ALL of the interfaces that use the directory.
#
# To avoid this, create separate dhcpcd configurations, one for the interfaces
# that should accept static routes and another for the interfaces that should
# not accept static routes routes.

# Add this script in the hooks directory only for the interfaces that should
# accept static routes.
#
# Add "nooption classless_static_routes, static_routes" to the dhcpcd.conf
# file for the interfaces that should not accept static routes. Do not add the
# script to the hooks directory.

next_set_interface=1

set_route_props_from_list()
{
    while [[ $# -ge 2 ]]; do
        setprop dhcp.${interface}.route${next_set_interface}.dest $1
        shift
        setprop dhcp.${interface}.route${next_set_interface}.via $1
        shift
        next_set_interface=$(($next_set_interface + 1))
    done
}

unset_route_props()
{
    next_clear_interface=1
    while [[ ! -z "$(getprop dhcp.${interface}.route${next_clear_interface}.dest)" ]]; do
      setprop dhcp.${interface}.route${next_clear_interface}.dest ""
      setprop dhcp.${interface}.route${next_clear_interface}.via ""
      next_clear_interface=$(($next_clear_interface + 1))
    done
    while [[ ! -z "$(getprop dhcp.${interface}.route${next_clear_interface}.via)" ]]; do
      setprop dhcp.${interface}.route${next_clear_interface}.dest ""
      setprop dhcp.${interface}.route${next_clear_interface}.via ""
      next_clear_interface=$(($next_clear_interface + 1))
    done
}

set_route_props()
{
    unset_route_props
    if [[ ! -z "${new_classless_static_routes}" ]]; then
        set_route_props_from_list ${new_classless_static_routes}
    else
        set_route_props_from_list ${new_static_routes}
    fi
}

case "${reason}" in
BOUND|INFORM|REBIND|REBOOT|RENEW|TIMEOUT)       set_route_props;;
EXPIRE|FAIL|IPV4LL|RELEASE|STOP)                unset_route_props;;
esac
