#!/bin/bash

# For Ethernet / WLAN interfaces we do miscellaneous
# configurations:
# - update resolv.conf for static config
# - make sure nscd sees any changed resolv.conf
# - announce our new address with ARP
# - emulate NetworkManager StateChanged signal
# - check ntpd so that it has all its server names resolved

# The resolv.conf file used for static IP config
STATICRESOLVCONF=/etc/network/resolv.conf.static

[ -n "$IFACE" ] || exit 1

# Skip if not inet or inet6
[ "$ADDRFAM" = "inet" -o "$ADDRFAM" = "inet6" ] || exit 0

# Skip if not of Ethernet or WLAN type
[ "$(< /sys/class/net/$IFACE/type)" = 1 ] || exit 0

# Setup /etc/resolv.conf for static / manual configuration
if [ -f "$STATICRESOLVCONF" ] && grep -q '[^[:space:]]' "$STATICRESOLVCONF"; then
    has_manual_resolv_conf=yes
else
    has_manual_resolv_conf=no
fi
# The resolv.conf is not to be modified if we do not have a manual resolver configuration,
# even if "$METHOD" is "static", because different address families may well have
# different methods and another address family may handle resolv.conf itself (e.g., DHCP)
if [ "$has_manual_resolv_conf" = "yes" ]; then
    cat "$STATICRESOLVCONF" > /etc/resolv.conf
fi

# Make sure nscd catches a changed /etc/resolv.conf
# (it can be changed by us above or by dhcp client before or something else)
nscd -i hosts 2>/dev/null

# Announce ourselves if we know the IPv4 address, zeroconf handles this itself
if [ "$ADDRFAM" = "inet" -a "$IF_ADDRESS" -a "$METHOD" != "zeroconf" ]; then
    # RFC3927 recommends 2 ARP packets 2 seconds apart
    arping -q -U -c 1 -I "$IFACE" "$IF_ADDRESS"
    sleep 2
    arping -q -U -c 1 -I "$IFACE" "$IF_ADDRESS"
fi

# Emulate NetworkManager StageChanged signal (70 = NM_STATE_CONNECTED_GLOBAL)
dbus-send --system --type=signal /org/freedesktop/NetworkManager org.freedesktop.NetworkManager.StateChanged uint32:70 2>/dev/null || :

# Check that ntpd got all its servers OK, if not the script will restart ntpd
[ -x /etc/spinetix/ntp-check ] && /etc/spinetix/ntp-check

exit 0
