#!/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
CPUFREQ_SET=/usr/bin/cpufreq-set

# Which governor to use. Must be one of the governors listed in:
#   cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors
#
# and which limits to set. Both MIN_SPEED and MAX_SPEED must be values
# listed in:
#   cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies
# a value of 0 for any of the two variables will disabling the use of 
# that limit variable.
#
# WARNING: the correct kernel module must already be loaded or compiled in.
# 
# Set ENABLE to "true" to let the script run at boot time.
# 
# eg:	ENABLE="true"
#	GOVERNOR="ondemand"
#	MAX_SPEED=1000
#	MIN_SPEED=500

ENABLE="true"
GOVERNOR="ondemand"
MAX_SPEED="0"
MIN_SPEED="0"

check_governor_avail() {
	info="/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors"
	if [ -f "$info" ] && grep -Fqw -- "$GOVERNOR" "$info" ; then
		return 0;
	fi
	return 1;
}

if [ -f /etc/default/cpufrequtils ] ; then
	. /etc/default/cpufrequtils
fi

if [ "$ENABLE" != "true" ] ; then
	echo "CPUFreq Utilities: disabled"
	exit 0
fi

if ! check_governor_avail ; then
	printf 'CPUFreq Utilities: disabled, governor %s not available\n' "$GOVERNOR"
	exit 0
fi

set --
if [ -n "$MAX_SPEED" ] && [ "$MAX_SPEED" != "0" ] ; then
	set -- "$@" --max "$MAX_SPEED"
fi

if [ -n "$MIN_SPEED" ] && [ "$MIN_SPEED" != "0" ] ; then
	set -- "$@" --min "$MIN_SPEED"
fi

if [ -n "$GOVERNOR" ] ; then
	set -- "$@" --governor "$GOVERNOR"
fi

CPUS=$(sed -ne 's/^cpu\([[:digit:]]\+\).*/\1/p' /proc/stat) || exit $?
RETVAL=0
for cpu in $CPUS ; do
	printf 'CPUFreq Utilities: setting %s governor on CPU%s\n' "$GOVERNOR" "$cpu"
	"$CPUFREQ_SET" --cpu "$cpu" "$@" || RETVAL=$?
done

exit "$RETVAL"
