#!/bin/sh
# 
# Keep the fan off
# This script will toggle the CPU frequency to keep
# the temperature below a certain level
# designed for FreeBSD
# Author: Alexander Kühn
# Web http://www.nagilum.org/#p
#
# Adjust the settings for your machine!
# Press Ctrl+C to stop it, 
# the script will print an average frequency on exit
# 
# the two frequencies to switch between
lowfreq=733
highfreq=1133

# the temperature at which to switch to the lower freq
trigger_temp=69
# if temp drops below trigger_temp-threshold switch to higher freq again
threshold=3

# wait this many secs between checks when the temp is high
highpause=1
# wait this many secs between checks when the temp is low
lowpause=1

high=`expr 0`
low=`expr 0`

trap cleanup 1 2 3 6

cleanup() {
	echo "${high}/${low}"
	echo "scale=10;${lowfreq}+(${highfreq}-${lowfreq})*(${high}/(${high}+${low}))" |bc
	exit 0
}

while [ 1 ];do
	echo `date "+%H:%M:%S : " && sysctl dev.cpu.0.freq=${highfreq}`|xargs
	while [ `sysctl hw.acpi.thermal.tz0.temperature|cut -d: -f2|cut -d. -f1|tr -d " "` -lt ${trigger_temp} ];do
		high=`expr ${high} + ${highpause}`
		sleep ${highpause}
	done
	echo `date "+%H:%M:%S : " && sysctl dev.cpu.0.freq=${lowfreq}`|xargs
	while [ `sysctl hw.acpi.thermal.tz0.temperature|cut -d: -f2|cut -d. -f1|tr -d " "` -gt `expr ${trigger_temp} - ${threshold}` ];do
		low=`expr ${low} + ${lowpause}`
		sleep ${lowpause}
	done
done

