#!/bin/sh
PATH=/usr/bin:/bin:/usr/sbin:/sbin
# Converts Fahrenheit to Celcius
f2c() {
  /bin/echo `expr \( \( $1 - 32 \) \* 10 + 9 \) \/ 18`
}
# Converts Celcius to Fahrenheit
c2f() {
  /bin/echo `expr \( $1 \* 9 \) \/ 5 \+ 32`
}
# Kill the old fan controller
PID=$(/bin/pidof fancontrol)
if [ -n "$PID" ]
  then
	 kill -9 $PID
fi
update_interval=60
#T1 and T2 in fahrenheit - convert if necessary using c2f function
T1=96
T2=110
IDLERPM=0
RPM1=2700
RPM2=3500
while [ 1 ]
do
  #Find out current temperature
  T=`temperature g 0`
  T=${T##*=}
  C=`temperature g 0 | grep -i -c centigrade `
# Convert to Fahrenheit if output is in Celcius
if [ $C -gt 0 ]
then
  C=$T
  F=$(c2f $C)
  T=$F
else
  F=$T
  C=$(f2c $F)
fi
#Search dmesg for hard drive messages
DRIVE0_dmesg=`/bin/dmesg | /bin/grep HD0 | /bin/tail -1`
DRIVE1_dmesg=`/bin/dmesg | /bin/grep HD1 | /bin/tail -1`
DRIVE0_awake=`/bin/dmesg | /bin/grep HD0 | /bin/tail -1 | /bin/grep awake`
DRIVE1_awake=`/bin/dmesg | /bin/grep HD1 | /bin/tail -1 | /bin/grep awake`
# Calculate new fanspeed, depending on if drives are awake or not
if [ -n "${DRIVE0_dmesg}"  ] && [ -n "${DRIVE1_dmesg}" ]; then
# True if dmesg contains status for both drives
if [ -n "${DRIVE0_awake}"  ] || [ -n "${DRIVE1_awake}" ]; then
# True if any of the drives are awake, keep fan running
newRPM=`expr \( \( $T2 \< $F \) \* $RPM2 \) \| \( \( $RPM1 + \( $RPM2 - $RPM1 \) \* \( $F - $T1 \) \/ \( $T2 - $T1 \) \) \& \( $F \>= $T1 \) \)`
else
	# None of the drives is awake, now check if Temperature is above $T1
        if [ $T -gt $T1 ]; then
                #Keep the fan running until the NAS has cooled down
                newRPM=$RPM1
        else
                #set speed to IDLE speed
                newRPM=$IDLERPM
        fi
fi
else
# dmesg does not yet contain the status for both drives
# (at least one of the drives has never been powered down), keep fan running
newRPM=`expr \( \( $T2 \< $F \) \* $RPM2 \) \| \( \( $RPM1 + \( $RPM2 - $RPM1 \) \* \( $F - $T1 \) \/ \( $T2 - $T1 \) \) \& \( $F \>= $T1 \) \)`
fi
# Set the new fan speed
fanspeed w $newRPM
# Wait for next cycle
/bin/sleep $update_interval
done
