#!/bin/sh
# bee-network.sh — bring up all physical network interfaces via DHCP
# Unattended: runs silently, logs results, never blocks.

LOG_PREFIX="bee-network"

log() { echo "[$LOG_PREFIX] $*"; }

list_interfaces() {
    ip -o link show \
        | awk -F': ' '{print $2}' \
        | grep -v '^lo$' \
        | grep -vE '^(docker|virbr|veth|tun|tap|br-|bond|dummy)' \
        | sort
}

# Give udev a short chance to expose late NICs before the first scan.
if command -v udevadm >/dev/null 2>&1; then
    udevadm settle --timeout=5 >/dev/null 2>&1 || log "WARN: udevadm settle timed out"
fi

started_ifaces=""
started_count=0
scan_pass=1

# Some server NICs appear a bit later after module/firmware init. Do a small
# bounded rescan window without turning network bring-up into a boot blocker.
while [ "$scan_pass" -le 3 ]; do
    interfaces=$(list_interfaces)

    if [ -n "$interfaces" ]; then
        for iface in $interfaces; do
            case " $started_ifaces " in
                *" $iface "*) continue ;;
            esac

            log "bringing up $iface"
            if ! ip link set "$iface" up; then
                log "WARN: could not bring up $iface"
                continue
            fi

            carrier=$(cat "/sys/class/net/$iface/carrier" 2>/dev/null || true)
            if [ "$carrier" = "1" ]; then
                log "carrier detected on $iface"
            else
                log "carrier not detected yet on $iface"
            fi

            # DHCP in background — non-blocking, keep dhclient verbose output in the service log.
            dhclient -4 -v -nw "$iface" &
            log "DHCP started for $iface (pid $!)"

            started_ifaces="$started_ifaces $iface"
            started_count=$((started_count + 1))
        done
    fi

    if [ "$scan_pass" -ge 3 ]; then
        break
    fi
    scan_pass=$((scan_pass + 1))
    sleep 2
done

if [ "$started_count" -eq 0 ]; then
    log "no physical interfaces found"
    exit 0
fi

log "done (interfaces started: $started_count)"
