#!/bin/sh
#
#
# chkconfig: 345 04 05
# description: This startup script disables NetworkManager on already up ifaces
#              and set up them to use dhcpcd -p

WITHOUT_RC_COMPAT=1


# Source function library.
. /etc/init.d/functions
. /bin/shell-config

RETVAL=0
DHCP_ARGS="--request -p -b"

find_up_ethernets () {
	local ifname
	local type
	local state
	local carrier
	local TYPE_ETHERNET=1  # see include/uapi/linux/if_arp.h
	for d in /sys/class/net/*; do
		ifname="${d##*/}"
		# skip non-ethernet interfaces
		# XXX: should I also consider VLANs, bridges, etc?
		type=`cat "$d/type"`
		if [ "$type" != "$TYPE_ETHERNET" ]; then
			continue
		fi
		carrier=`cat "$d/carrier"`
		if [ "$carrier" != "1" ]; then
			continue
		fi
		state=`cat "$d/operstate"`
		if [ "$state" != 'up' ]; then
			continue
		fi
		echo "$ifname"
	done
}

booted_from_network_fs () {
	egrep -q 'automatic[=]method[:]((nfs)|(cifs))' /proc/cmdline
}

start()
{
	local iface
	if ! booted_from_network_fs; then
		exit 0
	fi
	iface="$(find_up_ethernets | head -1)"
	mkdir -p /etc/net/ifaces/$iface
	shell_config_set /etc/net/ifaces/$iface/options NM_CONTROLLED 'no'
	shell_config_set /etc/net/ifaces/$iface/options DISABLED 'no'
	shell_config_set /etc/net/ifaces/$iface/options BOOTPROTO 'dhcp'
	shell_config_set /etc/net/ifaces/$iface/options DHCP_ARGS "'$DHCP_ARGS'"
	ip link set dev $iface multicast on
	dhcpcd $DHCP_ARGS $iface
	true
}

stop()
{
	true
}

restart()
{
	stop
	start
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	*)
		msg_usage "${0##*/} {start|stop}"
		RETVAL=1
esac

exit $RETVAL
