#! /bin/sh
# 
# Laptop mode tools module: Ethernet power saving tweaks.
#

if [ x$CONTROL_ETHERNET = x1 ] ; then
	if [ $ON_AC -eq 1 ]; then
		if [ "$ACTIVATE" -eq 1 ]; then
			THROTTLE_ETHERNET="$LM_AC_THROTTLE_ETHERNET"
		else
			THROTTLE_ETHERNET="$NOLM_AC_THROTTLE_ETHERNET"
		fi
	else
		THROTTLE_ETHERNET="$BATT_THROTTLE_ETHERNET"
	fi
	
	for DEVICE in $ETHERNET_DEVICES ; do
		# Wakeup-on-LAN handling
		if [ x$DISABLE_WAKEUP_ON_LAN = x1 ] ; then
			ret=`ethtool -s $DEVICE wol d 2>&1`
                        exit_status=$?;
			log "VERBOSE" "$ret"
			if [ $exit_status -eq 0 ]; then			
				log "VERBOSE" "Enabled wakeup-on-LAN for $DEVICE"
			else
				log "VERBOSE" "Could not enable wakeup-on-LAN for $DEVICE"
			fi
		fi
		
		# Determine speed
		speed=`mii-tool -v $DEVICE | grep capabilities | tr ' ' '\n' |\
                        sort -n | sed -ne '/^1.*/p' | cut -d "b" -f1`
                if [ -z "$speed" ]; then
                        speed=0;
                fi
		max_s=0;
		min_s=100000;
		for s in $speed;
		do
			if [ $s -gt $max_s ]; then
				max_s=$s
			fi
			if [ $s -lt $min_s ]; then
				min_s=$s
			fi
		done
		MAX_SPEED=$max_s;

		case "$THROTTLE_SPEED" in
			"slowest")
			THROTTLE_SPEED=$min_s
			;;
			"fastest")
			THROTTLE_SPEED=$max_s
			;;
		esac

		# Handle throttling
		if [ x$THROTTLE_ETHERNET = x1 ] ; then
			# Handle auto-negotiation
			ret=`ethtool -s $DEVICE autoneg off 2>&1`
                        exit_status=$?;
                        log "VERBOSE" "$ret";
			if [ $exit_status -eq 0 ]; then
				log "VERBOSE" "Switched auto-negotiation to off for $DEVICE"
			else
				log "VERBOSE" "Could not set auto-negotiation to off for $DEVICE"
			fi

			# Handle Speed Throttling
			ret=`ethtool -s $DEVICE speed $THROTTLE_SPEED 2>&1`
                        exit_status=$?;
                        log "VERBOSE" "$ret";
			if [ $exit_status -eq 0 ]; then
				log "VERBOSE" "Throttled speed to $THROTTLE_SPEED Mbit for $DEVICE"
			else
				log "VERBOSE" "Could not throttle speed for $DEVICE"
			fi
		else
			# Handle auto-negotiation
			ret=`ethtool -s $DEVICE autoneg on 2>&1`
                        exit_status=$?;
                        log "VERBOSE" "$ret";
			if [ $exit_status -eq 0 ]; then
				log "VERBOSE" "Switched auto-negotiation to on for $DEVICE"
			else
				log "VERBOSE" "Could not set auto-negotiation to on for $DEVICE"
			fi

			# Handle Speed Throttling
			ret=`ethtool -s $DEVICE speed $MAX_SPEED 2>&1`
                        exit_status=$?;
                        log "VERBOSE" "$ret";
			if [ $exit_status -eq 0 ]; then
				log "VERBOSE" "Restored speed to $MAX_SPEED Mbit for $DEVICE"
			else
				log "VERBOSE" "Could not restore speed for $DEVICE"
			fi
		fi
	done
else
	log "VERBOSE" "Ethernet module is disabled."
fi
