#!/bin/sh

# For disks resilients to spindown you can use this script.
# The script uses the timeout values set in the web page Disk->utilities->Spindown entry,
# even if you change it while it is executing
# It logs its activity to the system log, so you can see what it is doing
#
# If you watch constant spinup/spindown disk activity, be warned that there are physical
# mechanical limits on the number of spinup/dowwn that a harddisk can support.
# Read its specifications and use SMART (Disk->Util->Health-Show status).
#
# Start by copying it to one of your disk filesystems, e.g /mnt/sda2/spindown.sh
# Then ssh/telnet the box, copy it to /tmp, make it executable and start it in the background:
#
#   cp /mnt/sda2/spindown.sh /tmp/spindown.sh
#   chmod +x /tmp/spindown.sh
#   /tmp/spindown.sh &
#
# For now, you have to follow this procedure everytime the box reboots

# $1=sdk
dstat() {
	eval $(awk '{printf "time=%d; rw=%d;", systime(), $1 + $5}' /sys/block/$1/stat)

	last_rw=$(eval echo \$${1}_last_rw)
	timer=$(eval echo \$${1}_timer)

	if test "$last_rw" != "$rw"; then
		timer=0
		last_rw=$rw
	else
		timer=$((timer+1))
		if test "$timer" -gt "$timeout"; then
			if ! hdparm -C /dev/$1 | grep -q standby ; then 
				logger -t spindown "Spinning down $1"
				hdparm -y /dev/$1 >& /dev/null
			fi
		fi
	fi

	eval ${1}_last_rw=$rw
	eval ${1}_timer=$timer
}

while true; do

	if test -f /etc/misc.conf; then
		. /etc/misc.conf
	fi
	if test -f /etc/bay; then
		. /etc/bay
	fi

	for i in /dev/sd?; do
		dsk=$(basename $i)
		eval timeout=$(echo \$HDSLEEP_$(eval echo \$$dsk) | tr 'a-z' 'A-Z')
		dstat $dsk
	done

#	Uncomment the next line (remove the leading #) to watch in the system log how it works
#	logger -t spindown "sda_timer=$sda_timer sda_rw=$sda_last_rw sdb_timer=$sdb_timer sdb_rw=$sdb_last_rw"

	sleep 60
done
