#!/bin/bash -efu

. altboot-sh-functions
. altboot-net-functions

bring_up=


# Entry point
debug "$PROG started"
IM_start_output ponder errmsg

# Feature 'network' absent
if ! has_feature network; then
	message "feature 'network' absent inside initramfs"

	if [ -z "$NOASKUSER" ]; then
		msg="This disk builded without networking support."
		msg="$msg Booting by any network protocol is inpossible."
		IM_errmsg "$msg $IM_RBMSG"
	fi

	bc_reboot
fi

# No network settings
if [ "${IP:-0}" = 0 ] &&
	[ "${ROUTE:-0}" = 0 ] &&
	[ "${IFNAME:-0}" = 0 ] &&
	[ "${NAMESERVER:-0}" = 0 ]
then
	msg="network settings not defined in /proc/cmdline"

	if [ ! -d /proc/sys/net/ipv4 ]; then
		msg="IPv4 not available, $msg"
		[ -z "$NOASKUSER" ] ||
			fatal "$msg, dialogs are disabled"
		message "$msg"
		msg="$msg. Try with the option 'ip=dhcp4' after reboot."
		IM_errmsg "$msg $IM_RBMSG"
		bc_reboot
	fi

	message "$msg"

	{ echo 'export IP="1"'
	  echo 'export ROUTE="0"'
	  echo 'export IFNAME="0"'
	  echo 'export NAMESERVER="0"'
	  echo 'export IP0="dhcp4"'
	} >> /.initrd/initenv

	/lib/initrd/cmdline.d/network >/dev/null 2>&1 ||
		IM_fatal "can't reconfigure network settings"
	bring_up=1
fi

# Wait network only once
if [ ! -s "$NETBOOT_IFNAME" ]; then
	IM_ponder_start "[ Bringing up network... ]"

	n=240
	netdev=
	ifaces=' '
	while [ $n -gt 0 ]; do
		# shellcheck disable=SC2012
		for netdev in $(ls /sys/class/net/) lo; do
			[ "$netdev" != lo ] ||
				continue
			[ -r "/sys/class/net/$netdev/flags" ] ||
				continue
			if [ -n "$bring_up" ] && [ -n "${ifaces##* "$netdev" *}" ]; then
				echo add >"/sys/class/net/$netdev/uevent"
				ifaces="$ifaces $netdev "
			else
				ip -4 addr show dev "$netdev" 2>/dev/null |
					grep -qs '    inet ' && break 2 ||:
			fi
		done
		netdev=
		sleep 0.2
		n=$(( $n - 1 ))
	done
	unset n ifaces

	IM_ponder_stop

	if [ -n "$netdev" ]; then
		message "network device $netdev ready to connection"
		echo "$netdev" >"$NETBOOT_IFNAME"
	else
		message "connection timeout"

		if [ -z "$NOASKUSER" ]; then
			msg="Couldn't bring up network interface. Try with other"
			msg="$msg network settings, wired connection and/or cable."
			IM_errmsg "$msg"
		fi

		altboot_restart
	fi
fi

# shellcheck disable=SC2119
bypass_results
debug "$PROG finished"
