#!/bin/sh
#
# livecd-net-eth	Try to autoconfigure ethernet interfaces
#
# chkconfig: 345 05 95
# description:	aimed at livecd use

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

# Source function library.
. /etc/init.d/functions

LOCKFILE=/var/lock/subsys/livecd-net-eth
RETVAL=0

prefix="/etc/net/ifaces"

list_eth() {
	local sysdir=/sys/class/net
	[ -d "$sysdir" ] || return 1
	find "$sysdir" -mindepth 1 -maxdepth 1 -xtype d -printf '%f\n' |
		while read iface; do
			read type < "$sysdir/$iface/type"
			[ "$type" = 1 ] && echo "$iface"	# ethernet
		done
}

setup_eth() {
	[ -n "$1" ] || return 1
	[ -d "$prefix" ] || return 2
	local ifacedir="$prefix/$1"
	[ ! -d "$ifacedir" ] || return 0
	echo -n "$1 "
	# NB: 3 seconds means STP ports will stay down => unconfigured
	mkdir -p "$ifacedir" && {
		echo TYPE=eth
		echo BOOTPROTO=dhcp
		echo DHCP_TIMEOUT=7
	} > "$ifacedir/options"
}

. shell-config

start()
{
	[ -z "${BOOTPROTO:-}" ] || exit 0	# propagator + netboot
	echo -n "Configuring network: "

	# aufs bug workaround
	touch /etc/resolv.conf

	netcfg="/etc/sysconfig/network"

	shell_config_set "$netcfg" NETWORKING yes
	shell_config_set "$netcfg" HOSTNAME "$HOSTNAME"
	shell_config_set "$netcfg" DOMAINNAME "$DOMAINNAME"

	if  [ -x /usr/sbin/NetworkManager -o -x /usr/sbin/connmand ] ; then
		echo -n "skipped (interactive)"
		echo_success
		echo
		RETVAL=0
	else
		# attempt to autoconfigure ethernet by etcnet
		if [ -x /sbin/dhcpcd -o -x /sbin/dhclient ]; then
			ifaces="$(list_eth)"
			if [ -n "$ifaces" ]; then
				for i in $ifaces; do
					setup_eth "$i"
				done
			fi
			echo_success
			echo
			RETVAL=0
		else
			echo -n "skipped (DHCP client missing)"
			echo_passed
			echo
			RETVAL=1
		fi
	fi
	return $RETVAL
}

# See how we were called.
case "$1" in
	start|restart|reload)
		start
		;;
	stop)
		;;
	condstop)
		;;
	condrestart|condreload)
		if [ -e "$LOCKFILE" ]; then
			start
		fi
		;;
	status)
		;;
	*)
		msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status}"
		RETVAL=1
esac

exit $RETVAL
