#!/bin/sh -efu
### This file is covered by the GNU General Public License
### version 2 or later.
###
### Copyright (C) 2018  ALT Linux Team
### Author: Leonid Krivoshein <klark@altlinux.org>

if [ -z "${__included_rescue_launcher_network-}" ]; then
__included_rescue_launcher_network=1

# Bridge up network
autorun_networking() {
	local up=0 ip="ip" dhcpcd="dhcpcd" i= iface=

	autorun_debug "Bridging up network..."
	autorun_spawn test -n "${AUTORUN_SERVER-}" || return 1
	autorun_spawn test -n "${AUTORUN_DIRECTORY-}" || return 1
	autorun_spawn test -d /sys/class/net || return 1
	autorun_spawn which $ip || return 1
	autorun_spawn which $dhcpcd || return 1

	echo "Connecting to network..."

	for iface in $(ls -1 /sys/class/net/ | grep -v wlan) _; do
		if [ "$(cat "/sys/class/net/$iface/type" ||:)" = "1" ]; then
			autorun_debug "Probing with interface $iface..."
			if $ip addr show dev $iface 2>/dev/null |
				grep -qE '^[[:space:]]+inet '
			then
				up=1
				break
			elif autorun_spawn $dhcpcd -t 40 $iface; then
				for i in $(seq 1 20); do
					if $ip addr show dev $iface 2>/dev/null |
						grep -qE '^[[:space:]]+inet '
					then
						up=1
						break 2
					fi
					sleep .5
				done
			else
				autorun_spawn killall $dhcpcd ||:
			fi
		fi
	done

	test $up -ne 0 || return 1
	export AUTORUN_NETOK=1

	return 0
}

fi #__included_rescue_launcher_network
