# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Copyright 2015-2022 SUSE LLC

do_wicked_autoconfig()
{
	d --infobox $"Collecting network info ..." 3 33

	shopt -s nullglob

	for net_path in /sys/class/net/*; do
		[ -d "$net_path" ] || continue # skip bonding_masters file

		net_device=${net_path##*/}

		[ "$net_device" = "lo" ] && continue

		# Only devices having ID_NET_NAME.* attrs
		# Ignore errors if udev not available
		udevadm info -q property -p "$net_path" 2>/dev/null | grep -qs ID_NET_NAME || continue
		# But don't touch WLAN interfaces
		udevadm info -q property -p "$net_path" | grep -qs "DEVTYPE=wlan" && continue

		unset IPADDR
		eval `wicked test dhcp4 "$net_device" 2>/dev/null | grep -E "^IPADDR="`
		ip link set down "$net_device" # set link down after probe once done

		# Create a configuration file for each interface that provides
		# an IPADDR
		if [ -n "$IPADDR" ]; then
			printf "STARTMODE=auto\nBOOTPROTO=dhcp\n" \
				> "/etc/sysconfig/network/ifcfg-$net_device"
		fi
	done

	run sed -i -E 's/^DHCLIENT(6?)_SET_HOSTNAME=.*$/DHCLIENT\1_SET_HOSTNAME=yes/' /etc/sysconfig/network/dhcp
}

network_jeos_config()
{
	if ! dialog --backtitle "$PRETTY_NAME" --yesno $"This will create a new network configuration from scratch,
all connections will be lost.\nDo you want to continue?" 7 50; then
		return
	fi
	do_wicked_autoconfig
	d --infobox $"Restarting network ..." 3 26 || true
	systemctl restart network
}

network_systemd_firstboot()
{
	do_wicked_autoconfig
}
