#!/bin/sh

##This file is mostly fixes stolen directly from the recommendations of powertop.
# For the sake of completeness we will include the fixes we don't want and comment them out with reasoning
# XXX: This should be rewritten into acpid and this file should just be an initial call to acpid default.sh
#---------------------------------------------------------------------------------------------------------

##PM runtime (PCI Devices)
##this links to usb and disables usb devices that suck
#for i in `find /sys/devices/pci* -name "control"`; do echo "auto" > $i; done

##USB Suspend
#all of this is too aggressive for most usb mice/keyboards
#for i in /sys/bus/usb/devices/*/power/autosuspend; do echo 1 > $i; done
#for i in /sys/bus/usb/devices/*/power/control; do echo auto > $i; done
#for i in /sys/bus/usb/devices/*/power/level; do echo auto > $i; done

# allowing to not sync the drive for longer on battery means more lost when we run out of battery, not a fan
#echo 1500 > /proc/sys/vm/dirty_writeback_centisecs

## This TANKS wifi performance way too much
#iwconfig wlan0 power timeout 500ms

#intel sound
if [ -e /sys/module/snd_hda_intel/parameters/power_save ]; then
	echo 1 > /sys/module/snd_hda_intel/parameters/power_save
fi


##Making devices take longer to power save means more draw
#USB suspend tweaking based on Linux/Documentation/usb/power-management.txt
#Change the default autosuspend idle value from 2sec to 60sec
#for i in /sys/bus/usb/devices/*/power/autosuspend_delay_ms; do echo 60000 > $i; done
#echo 60 > /sys/module/usbcore/parameters/autosuspend

#disable NMI watchdog (unless we are running a redundant kernel we don't need this)
if [ -e /proc/sys/kernel/nmi_watchdog ]
then
	echo 0 > /proc/sys/kernel/nmi_watchdog
fi

if [ -e /sys/devices/system/cpu/sched_mc_power_savings ]
then
	echo 1 > /sys/devices/system/cpu/sched_mc_power_savings
fi

##then the battery specific power savings
if [ "$(cat /sys/class/power_supply/AC*/online)" == "0" ]; then
	#battery
	if [ -e /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ]
	then
		for CPU in $(ls  /sys/devices/system/cpu/|grep -E "cpu[0-9]+"); do
			echo conservative > /sys/devices/system/cpu/${CPU}/cpufreq/scaling_governor
		done
	fi
	if [ -e /sys/class/scsi_host/host0/link_power_management_policy ]
	then
		for controller in $(ls /sys/class/scsi_host/|grep -E "host[0-9]+"); do
			echo min_power > /sys/class/scsi_host/${controller}/link_power_management_policy
		done
	fi
else
	#AC
	if [ -e /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ]
	then
		for CPU in $(ls  /sys/devices/system/cpu/|grep -E "cpu[0-9]+"); do
			echo ondemand > /sys/devices/system/cpu/${CPU}/cpufreq/scaling_governor
		done
	fi
	if [ -e /sys/class/scsi_host/host0/link_power_management_policy ]
	then
		for controller in $(ls /sys/class/scsi_host/|grep -E "host[0-9]+"); do
			echo max_performance > /sys/class/scsi_host/${controller}/link_power_management_policy
		done
	fi
fi
