#!/bin/sh

timeout=10 #minutes

# $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

	for i in /dev/sd?; do
		dstat $(basename $i)
	done

	logger -t spindown "sda_timer=$sda_timer sda_rw=$sda_last_rw sdb_timer=$sdb_timer sdb_rw=$sdb_last_rw"
	sleep 60
done
