#!/bin/sh
#
# This script was created at http://wiki.dns323.info by FIB,
# it has been slightly modified by leper (with help from
# fonz). It sets the fanspeed of the device depending on 
# the temperature, which is measured in Fahrenheit. If 
# your box measures temperature in Celsius, you need to 
# edit it to work.
# Additional changes by gartylad.
# Uriel : corrected zero fanspeed when T exceeded T2
#         minor code updates
 
# Set the path to use RAM-disk instead of harddrive, to 
# execute from. This is done so that the disks will go
# into sleep mode, while the script is running.
PATH=/usr/bin:/bin:/usr/sbin:/sbin
 
# Create a logfile on the RAM-disk.
LOGDIR=/log
FANLOGFILE=${LOGDIR}/fan_ctrl.log
mkdir -p ${LOGDIR}
 
echo "Installing fan_ctrl.sh" >${FANLOGFILE}
 
# Kill the old fancontrol process if required
OLDPID=`pidof fancontrol`
if [ "$OLDPID" != "" ]
then
  kill -9 $OLDPID
  echo "killed old fancontrol process ($OLPID)" >>${FANLOGFILE}
fi
 
 
 
# With temps between T1 and T2, the script automatically
# lowers/raises the fan speed between RPM1 and RPM2. This
# it does every update_interval seconds.
update_interval=60
T1=43
T2=60
RPM1=2300
RPM2=4500
RPM3=15000
DRPM_DT=`expr \( $RPM2 - $RPM1 \) / \( $T2 - $T1 \)`
 
 
while [ 1 ]
do
  T=`temperature g 0`
  T=${T##*=}
 
  # Check if temperature has fallen below T1 value
  if [ $T -lt $T1 ]; then
    # Temp below T1 fan stops
    NEWRPM=0
  elif [ $T -gt $T2 ]; then
    # Temp greater than T2 requires emergency action
    NEWRPM=$RPM3
  else
    # Compute new RPMs if in T1..T2 range
    NEWRPM=`expr $RPM1 + \( \( $T - $T1 \) \* $DRPM_DT \)`
  fi
 
 
  CONVFTOC=`expr \( \( $T - 32 \) \* 10 + 9 \) \/ 18`
  fanspeed w $NEWRPM  
  echo `date`" ::CURRENT::" $T"F" ${CONVFTOC}"C -- fanspeed:" $NEWRPM "(written to "${FANLOGFILE}")." >>${FANLOGFILE}
  # wait for next cycle
  sleep $update_interval
done