#!/bin/bash
# Averatec 32xx with custom DSDT fan control
# By Georgi Todorov terahzgeodar.com
# License: Attribution-ShareAlike 2.5
# http://creativecommons.org/licenses/by-sa/2.5/
# USE AT YOUR OWN RISK

TERM=/proc/acpi/thermal_zone/THRM/temperature
FAN=/proc/acpi/fan/FAN0/info

while [ true ];do
	read X Y Z < $TERM
	STATE=`tail -n 1 /proc/acpi/fan/FAN0/info|cut -d " " -f2`
	
	if [ $Y -lt 40 ]
	then
		if [ $STATE = 0 ] 
		then
			echo "GOOD"
		elif [ $STATE -gt 0 ]
		then
			echo "Temperature is $Y switching to state 0"
			echo 0 > /proc/acpi/fan/FAN0/info
		fi
	elif [ $Y -lt 45 ]
	then
		if [ $STATE -lt 1 ]
		then
			echo "Temperature is $Y switching to state 1"
			echo 1 > /proc/acpi/fan/FAN0/info
		elif [ $STATE = 1 ]
		then
			echo "Temperature is $Y and mode is $STATE - do not touch anything!"
		elif [ $STATE -gt 1 ]
		then
			echo "Temperature is $Y switching to state 1"
			echo 1 > /proc/acpi/fan/FAN0/info
		fi
	elif [ $Y -lt 50 ]
	then
		if [ $STATE -lt 2 ]
		then
			echo "Temperature is $Y switching to state 2"
			echo 2 > /proc/acpi/fan/FAN0/info
		elif [ $STATE = 2 ]
		then
			echo "Temperature is $Y and mode is $STATE - do not touch anything!"
		elif [ $STATE -gt 2 ]
		then
			echo "Temperature is $Y switching to state 2"
			echo 2 > /proc/acpi/fan/FAN0/info
		fi
		elif [ $Y -lt 55 ]
	then
		if [ $STATE -lt 3 ]
		then
			echo "Temperature is $Y switching to state 3"
			echo 3 > /proc/acpi/fan/FAN0/info
		elif [ $STATE = 3 ]
		then
			echo "Temperature is $Y and mode is $STATE - do not touch anything!"
		elif [ $STATE -gt 3 ]
		then
			echo "Temperature is $Y switching to state 3"
			echo 3 > /proc/acpi/fan/FAN0/info
		fi
	else
		if [ $STATE -ne 4 ]
		then
			echo "Temperature is $Y switching to state 4"
			echo 4 > /proc/acpi/fan/FAN0/info
		else
			if [ $Y -lt 65 ]
			then
				echo "Temperatyre is $Y and mode is $STATE - we can still handle it!"
			else
				echo "TOO HOT!!!!! TOO HOT!!!!"
			fi
		fi
	fi
	sleep 2
done