#!/bin/sh

# /etc/network/if-pre-up.d/dhcpcd-sync
#
# Hook script provided by the 'tkl-dhcpcd-ifupdown-glue' package and part of
# TurnKey GNU/Linux network configuration.
#
# Keeps dhcpcd.conf in sync with /etc/network/interfaces so that
# interfaces configured as static are not also managed by dhcpcd.

[ "$IFACE" = "lo" ] && exit 0
[ "$ADDRFAM" != "inet" ] && [ "$ADDRFAM" != "inet6" ] && exit 0

DHCPCD_CONF="/etc/dhcpcd.conf"

# Map address family to a token we use in markers and denyinterfaces
# dhcpcd uses "ip4" and "ip6" as address family suffixes in denyinterfaces
case "$ADDRFAM" in
    inet)  AF_TOKEN="ip4" ;;
    inet6) AF_TOKEN="ip6" ;;
    *)     exit 0 ;;
esac

# The deny entry format dhcpcd understands per address family
DENY_ENTRY="${AF_TOKEN}:${IFACE}"
MARKER="# ifupdown-managed: ${IFACE} ${AF_TOKEN} - edit /etc/network/infaces"

remove_deny_entry() {
    # Remove both the marker and the denyinterfaces line for this iface
    sed -i "/^${MARKER}$/{N;d}" "$DHCPCD_CONF"
}

add_deny_entry() {
    remove_deny_entry
    printf '\n%s\ndenyinterfaces %s\n' "$MARKER" "$DENY_ENTRY" >> "$DHCPCD_CONF"
}

case "$METHOD" in
    static|manual)
        add_deny_entry
        ;;
    dhcp)
        remove_deny_entry
        ;;
esac

exit 0
