#! /bin/sh
# 
# Laptop mode tools module, called from /usr/sbin/laptop_mode.
# Configuration in /etc/laptop-mode/conf.d/wireless-ipw-power.conf.
#
# PURPOSE: power saving for the Intel 3945 and 4965 adapters when using the
#          iwlwifi drivers.
#
# This script relies upon the name of the driver.
#

#
# Find all the wireless devices using the supplied driver names.
# Place the interface names on the list WIFI_IFNAMES.
#
findWifiIfsByDriver () {
	local DEVICE;
	local LINK_TARGET;

	for DEVICE in /sys/class/net/*; do
		if [ -d $DEVICE/wireless -a -h $DEVICE/device/driver ]; then
			# See if the driver for $DEVICE matches the supplied one by checking the link to
			# the driver.
			LINK_TARGET=`readlink $DEVICE/device/driver`
			LINK_TARGET=${LINK_TARGET##*/}
			
			if [ "$LINK_TARGET" = "$1" ] ; then
				# add the interface name to the list
				WIFI_IFNAMES="$WIFI_IFNAMES ${DEVICE##*/}"
			fi
		fi
	done
}

if [ x$CONTROL_IWL_POWER = x1 ] ; then
	$LM_VERBOSE && echo "Setting power levels for iwlwifi wireless interfaces." >> $OUTPUT

	# Provide defaults for config file settings
	[ "$IWL_AC_POWER" ]   || IWL_AC_POWER=6
	[ "$IWL_BATT_POWER" ] || IWL_BATT_POWER=7

	WIFI_IFNAMES=""
	[ -d /sys/module/iwl3945 ] && findWifiIfsByDriver iwl3945
	[ -d /sys/module/iwl4965 ] && findWifiIfsByDriver iwl4965
	[ -d /sys/module/iwlagn ] && findWifiIfsByDriver iwlagn
	for IF in $WIFI_IFNAMES ; do
		if [ $ON_AC -eq 1 ] ; then
			$LM_VERBOSE && echo "On AC power: setting power level for $IF to $IWL_AC_POWER." >> $OUTPUT
			if ( ! echo $IWL_AC_POWER > /sys/class/net/$IF/device/power_level ) ; then
				echo "Failed." >> $OUTPUT
			fi
		else
			$LM_VERBOSE && echo "On battery: setting power level for $IF to $IWL_BATT_POWER." >> $OUTPUT
			if ( ! echo $IWL_BATT_POWER > /sys/class/net/$IF/device/power_level ) ; then
				echo "Failed." >> $OUTPUT
			fi
		fi
	done
else
	$LM_VERBOSE && echo "Intel IWL Wireless power setting is disabled." >> $OUTPUT
fi
