#!/bin/sh
#
# Startup script for ethtool
#
# description: Tunes Ethernet cards if needed.
# chkconfig: - 11 89

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

LOCKFILE=/var/lock/subsys/ethtool
ETHTOOL=/usr/sbin/ethtool
ETHCFG=/etc/sysconfig/ethtool
IFCFG=/etc/sysconfig/network-scripts/ifcfg
PARAMS="speed duplex port autoneg phyad xcvr wol sopass msglvl"
N_C_S_CONFIG=/etc/sysconfig/network
SourceIfNotEmpty $N_C_S_CONFIG

[ "$CONFMETHOD" = "net-scripts" ] || exit 0
[ -x $ETHTOOL ] || exit 0

# if /etc/sysconfig/ethtool exists and contains non-zero ETH value, it is
# assumed as tuning configuration source for one specified network card;
# otherwise, ifcfg-eth* files are searched and get dealt with on
# per-interface basis.

SourceIfNotEmpty $ETHCFG && [ -n "$ETH" ] || exit 0

get_interfaces () {
	unset INTERFACES
	[ "$ETH" = all ] && {
		INTERFACES=`ls $IFCFG-eth* \
		| egrep 'eth[0-9]+$' \
		| sed 's,^.*ifcfg-,,'`
	} || {
		for i in $ETH; do
			[ -f $IFCFG-$i ] && INTERFACES="$INTERFACES $i";
		done
	}
	[ -z "$INTERFACES" ] && exit 0
	echo $INTERFACES
}

tune_interface () {
	# collect parameters from ground up; use them
	unset $PARAMS ARGS
	SourceIfNotEmpty $ETHCFG
	SourceIfNotEmpty $IFCFG-$1
	for parm in $PARAMS; do 
		value=`eval echo \\${$parm}`	# somewhat twisted
		[ -n "$value" ] && ARGS="$parm $value $ARGS"
	done
	$ETHTOOL -s $1 $ARGS
}

start()
{
	for i in `get_interfaces`; do
		echo -n "Tuning interface $i: "
		tune_interface $i && success "ethtool on $i" || failure "ethtool on $i"
		echo
	done
	RETVAL=$?
	touch $LOCKFILE
}

stop()
{
	rm $LOCKFILE
	exit 0
}

restart()
{
	start
}

status()
{
	echo -n "Subsystem was "
	[ -f $LOCKFILE ] || echo -n "not "
	echo "activated; ethtool reports the following:"
	for i in `get_interfaces`; do
		echo -e "\n* $i"
		$ETHTOOL -i $i
	done
	RETVAL=$?
}

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

exit $RETVAL
