#!/sbin/openrc-run
# SPDX-License-Identifier: MIT

# This is a much simpler version than alpine openrc's net-online service
# (unlike net-online, this stops if default route's bearing interface is up)

description="Waits until network comes up, or timeout"

depend()
{
	after modules net
	need sysfs
	provide network-online
	keyword -docker -jail -lxc -openvz -prefix -systemd-nspawn -uml -vserver
}


check_net() {
	local iface

	# OK if either ipv4 or ipv6 is up
	for ip in 1.0.0.0 1::; do
		iface=$(ip r get "$ip" 2>/dev/null | grep -oE "dev [^ ]*")
		iface=${iface#dev }
		[ -n "$iface" ] || continue

		[ "$(cat "/sys/class/net/$iface/carrier")" = 1 ] && return
	done

	return 1
}

start()
{
	local timeout=${timeout:-60}

	ebegin "Waiting for network to come up"

	while [ "$timeout" -gt 0 ]; do
		check_net && break
		sleep 1
		: $((timeout -= 1))
	done
	eend $((timeout == 0)) "Network did not come up"
}
