#!/bin/bash

# Automatic fan controller
# Tested on a eee 901 running Ubuntu 9.10 Karmic Koala

# Test with 'sudo eeefan background'.
# If works, 'sudo cp eeefan /etc/rc2.d/S99eeefan'
# and reboot.

temp_file=/sys/devices/virtual/thermal/thermal_zone0/temp
fan_control=/sys/devices/platform/eeepc/hwmon/hwmon1/pwm1
fan_control_activate=/sys/devices/platform/eeepc/hwmon/hwmon1/pwm1_enable

temp_fanspeeds=(
# temp fan_speed
  0    20
  56   35   # When temperature is >= 56, set fan speed to 30%.
  58   50
  60   75
  65   100 )

eeefanupdate() {
    TEMP=$(cat $temp_file)
    TEMP=$(($TEMP / 1000))

    i=0
    while [ $i -lt ${#temp_fanspeeds[@]} ]
    do
        if [ $TEMP -ge ${temp_fanspeeds[$i]} ]
        then
            FANSPEED=${temp_fanspeeds[$i+1]}
        fi
        i=$((i + 2))
    done
    FANSPEED=$(($FANSPEED * 250 / 100))

    echo $FANSPEED > $fan_control
}

case "$1" in
    start)
        start-stop-daemon --start --background --exec $0 -- background
        ;;
    background)
    sleep 70

    echo 1 > $fan_control_activate

    while [ 1 ]
    do
      eeefanupdate
      sleep 10
    done
    ;;
    stop)
        ;;
    *)
        echo "Usage: $0 start|background" >&2
        exit 3
        ;;
esac

