#!/bin/bash

pause=4
fan_path="/proc/acpi/ibm/fan"
logfile=~/.scriptlogs/my_fan_control.log
temp_inc1=52
temp_inc2=60
temp_inc3=68
temp_dec1=48
temp_dec2=55
temp_dec3=63
fan=1

# watchdog
# if the system recives no fan control commands for 20 seconds, the
# automatic fan control method of the os is loaded again
echo "watchdog 20" | sudo tee $fan_path

# get current CPU temperature
curr_temp=$(cat  /sys/class/hwmon/hwmon1/device/temp1_input)
let curr_temp=$curr_temp/1000
while true
do
	last_temp=$curr_temp
	curr_temp=$(cat  /sys/class/hwmon/hwmon1/device/temp1_input)
	let curr_temp=$curr_temp/1000

	if [ $curr_temp -gt 0 -a $curr_temp -lt 100 ]; then
		if [ $curr_temp -gt $last_temp ]; then
			if [ $curr_temp -ge $temp_inc3 ]; then
				fan=7
				echo level $fan | sudo tee $fan_path
				sleep $pause
				continue
			fi
			if [ $curr_temp -ge $temp_inc2 ]; then
				fan=4
				echo level $fan | sudo tee $fan_path
				sleep $pause
				continue
			fi
			if [ $curr_temp -ge $temp_inc1 ]; then
				fan=2
				echo level $fan | sudo tee $fan_path
				sleep $pause
				continue
			fi
			fan=1
			echo level $fan | sudo tee $fan_path
			sleep $pause
			continue
#		fi
		else
			if [ $curr_temp -le $temp_dec1 ]; then
				fan=1
				echo level $fan | sudo tee $fan_path
				sleep $pause
				continue
			fi
			if [ $curr_temp -le $temp_dec2 ]; then
				if [ $fan -ge 2 ]; then
					fan=2
				else
					fan=1
				fi
				echo level $fan | sudo tee $fan_path
				sleep $pause
				continue
			fi
			if [ $curr_temp -le $temp_dec3 ]; then
				if [ $fan -ge 4 ]; then
					fan=4
				else
					fan=2
				fi
				echo level $fan | sudo tee $fan_path
				sleep $pause
				continue
			fi
			fan=7
			echo level $fan | sudo tee $fan_path
			sleep $pause
			continue
		fi
	else
		echo "current temp couldn't be parsed, curr_temp = $curr_temp, exiting..." >> $logfile
		exit 1;
	fi
done
exit 0
