#!/bin/bash

# For Ethernet interfaces (e.g., eth0) configured with static IP
# address check that the intended address is not already in use.

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

# Skip if not inet
[ "$ADDRFAM" = "inet" ] || exit 0

# Skip if not eth
[ "${IFACE%[0-9]*}" = "eth" ] || exit 0

# Skip if not static assignment
[ "$METHOD" = "static" ] || exit 0

# Check that there is an IP address
[ -n "$IF_ADDRESS" ] || exit 1

# Flush leftover IPv4 addresses from interface, so that it has none when
# we bring it up (other addresses managed by other daemons may be active,
# we leave those alone based on the label)
ip -4 addr flush dev "$IFACE" label "$IFACE" 2>/dev/null

# Bring up the interface
if ! ip link set "$IFACE" up; then
    echo "ERROR: cannot enable $IFACE" >&2
    exit 1
fi

# Perform duplicate address detection (RFC2131, 4.4.1 and RFC3927, 2.2.1)
# We run it at the highest possible priority so that it does not timeout
# due to lack of scheduling.
nice -n -20 arping -q -c 3 -w 3 -D -I "$IFACE" "$IF_ADDRESS"
RET_DAD=$?
if [ $RET_DAD -ne 0 ]; then
    echo "IP address $IF_ADDRESS is already in use, failing $IFACE" >&2
fi

# NOTE: we do not bring down the interface, because we want to
# keep its IPv6 address alive, link detection, etc.
#if ! ip link set "$IFACE" down; then
#    echo "ERROR: cannot disable $IFACE" >&2
#fi

exit $RET_DAD
