#!/bin/bash
#
# Copyright VyOS maintainers and contributors <maintainers@vyos.io>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

DHCP_HOOK_IFLIST="/tmp/static_dhcp_interfaces"

# Only run if there are static routes with dhcp-interface configured
if ! { [ -f $DHCP_HOOK_IFLIST ] && grep -qw $interface $DHCP_HOOK_IFLIST; }; then
    return 0
fi

# Handle interface state changes that require static route regeneration
# - PREINIT: interface is about to be configured, cleanup old routes
# - EXPIRE: lease has expired, remove routes
# - FAIL: DHCP failed, remove routes
# - RELEASE: lease released, remove routes
# - STOP: dhclient stopped, remove routes
if [ "$reason" == "PREINIT" ] || [ "$reason" == "EXPIRE" ] || [ "$reason" == "FAIL" ] || [ "$reason" == "RELEASE" ] || [ "$reason" == "STOP" ]; then
    # Re-generate static routes config to remove routes that depend on this interface
    sudo /usr/libexec/vyos/vyos-request-configd-update.py
fi
