#!/bin/sh

set -eu

interface="${1:-}"
sysfs_root="${ZEROARM_SYSFS_ROOT:-/sys/class/net}"
interface_root="$sysfs_root/$interface"
avahi_autoipd="${ZEROARM_AVAHI_AUTOIPD:-/usr/sbin/avahi-autoipd}"
action_script="${ZEROARM_IPV4LL_ACTION:-/usr/lib/zeroarm/zeroarm-host-ipv4ll.action}"
poll_seconds="${ZEROARM_IPV4LL_POLL_SECONDS:-2}"
missing_grace_seconds="${ZEROARM_IPV4LL_MISSING_GRACE_SECONDS:-20}"
child_pid=""
child_elapsed=0

stop_child() {
  if test -n "$child_pid" && kill -0 "$child_pid" 2>/dev/null; then
    kill "$child_pid" 2>/dev/null || true
    wait "$child_pid" 2>/dev/null || true
  fi
  child_pid=""
  child_elapsed=0
}

trap 'stop_child; exit 0' INT TERM

has_carrier() {
  test -r "$interface_root/carrier" \
    && test "$(cat "$interface_root/carrier" 2>/dev/null)" = "1"
}

has_ipv4ll_address() {
  ip -4 -o address show dev "$interface" 2>/dev/null \
    | grep -q ' inet 169\.254\.'
}

start_child() {
  "$avahi_autoipd" --syslog --force-bind \
    --script="$action_script" "$interface" &
  child_pid=$!
  child_elapsed=0
}

# Stay alive for the lifetime of the physical interface. Carrier transitions do
# not reliably emit a udev event on every Linux/NIC combination, so a one-shot
# service cannot guarantee that IPv4LL comes back after unplug/replug.
while :; do
  if ! has_carrier; then
    stop_child
  elif test -z "$child_pid"; then
    start_child
  elif ! kill -0 "$child_pid" 2>/dev/null; then
    wait "$child_pid" 2>/dev/null || true
    child_pid=""
    start_child
  else
    child_elapsed=$((child_elapsed + poll_seconds))
    # RFC 3927 probing and announcement normally takes about ten seconds. If
    # NetworkManager later flushes the foreign address, recycle autoipd so the
    # address and the two Ethernet-specific /17 routes are restored.
    if test "$child_elapsed" -ge "$missing_grace_seconds" \
        && ! has_ipv4ll_address; then
      stop_child
    fi
  fi

  sleep "$poll_seconds"
done
