#!/bin/sh
# hardwire eth0 at 192.168.0.1/24

. install2-init-functions

cd /sys/class/net

# yes if none, it's intended (for preconfiguration with no driver)
single_iface() { [ "`echo eth* | wc -w`" = 1 ]; }

# preserve errorlevel just in case it's ever needed
test_speed() {
	[ -d "$1" ] && {
		. "$1/device/uevent"
		if [ "$DRIVER" = virtio_net ]; then
			echo 1		# a token speed
		else
			if ip link set up dev "$1"; then
				cat "$1/speed"
			else
				echo 0	# at least it's there
			fi
		fi
	}
}

# 3 seconds is a result of a haggle with netch@
test_dhcp() { dhcpcd -t 3 -T -q $i >&2; }

# try to save what's there already
copy_rules() {
	local f=/etc/udev/rules.d/70-persistent-net.rules
	[ -s "$f" ] && cp -a "$f" "$destdir$f"	# ...or return non-zero
}

# persistence isn't futile
write_rule() {
	copy_rules && return
	[ -d "$1" ] || return
	INTERFACE="$1" \
	MATCHADDR="`cat "$1/address"`" \
		chroot "$destdir" /lib/udev/write_net_rules
}

# the heuristic is:
# - choose the fastest of interfaces getting DHCP replies for INET_ETH;
# - choose the fastest of the rest for LTSP_ETH;
# - do NOT configure any of DHCP interfaces for LTSP_IP
#   since our dhcpd will sit there

LTSP_SPEED=-1
INET_SPEED=-1

if single_iface; then
	test_dhcp eth0 && INET_ETH=eth0 || LTSP_ETH=eth0
else
	for i in eth*; do
		SPEED="`test_speed "$i"`"
		if test_dhcp "$i"; then
			if [ "$SPEED" -gt "$INET_SPEED" ]; then
				INET_SPEED="$SPEED"
				INET_ETH="$i"
			fi
		else
			if [ "$SPEED" -gt "$LTSP_SPEED" ]; then
				LTSP_SPEED="$SPEED"
				LTSP_ETH="$i"
			fi
		fi
	done
fi

# last effort
if [ -z "$LTSP_ETH$INET_ETH" ]; then
	test_dhcp eth0 && NO="# DHCP detected, disable ours\n#"
	LTSP_ETH=eth0
fi

# this default is hardwired in several more places at the moment,
# see also http://www.altlinux.org/LTSP/Network
LTSP_IP="192.168.0.1/24"

IFACEDIR="$destdir/etc/net/ifaces"

if [ -n "$LTSP_ETH" ]; then
	write_rule "$LTSP_ETH"
	mkdir -p "$IFACEDIR/$LTSP_ETH"
	echo -e "$NO$LTSP_IP" > "$IFACEDIR/$LTSP_ETH/ipv4address"
	cat > "$IFACEDIR/$LTSP_ETH/options" <<-EOF
	${LTSP_SPEED:+# speed: $LTSP_SPEED}
	TYPE=eth
	BOOTPROTO=static
	NM_CONTROLLED=no
	DISABLED=no
	EOF
fi

if [ -n "$INET_ETH" ]; then
	write_rule "$INET_ETH"
	mkdir -p "$IFACEDIR/$INET_ETH"
	cat > "$IFACEDIR/$INET_ETH/options" <<-EOF
	${INET_SPEED:+# speed: $INET_SPEED}
	TYPE=eth
	BOOTPROTO=dhcp
	NM_CONTROLLED=no
	DISABLED=no
	EOF
fi
