#!/bin/zsh
# This script watches the IO registry to keep track of activity on the input
# devices. Once an inactivity threshold has been reached, HDD spindown will be
# enabled. The idea here is to always keep the drives spun up while you are
# active on the computer, but to let them spin down when you are away. This
# script aims to eliminate the lengthy delays waiting for a disk to spin up
# during a computing session.

# Set your desired threshold here, in minutes
limit=15

# convert to seconds
limit_s=$((limit * 60))

# Store the most recent state so we don't reset disk sleep unnecessarily
laststate='wake'

echo -n `date`
echo " disksleep starting with sleep threshold of $limit minutes"

# loop
while true
do

# get idle time
idle=$((`ioreg -c IOHIDSystem | sed -e '/HIDIdleTime/ !{ d' -e 't' -e '}' -e 's/.* = //g' -e 'q'` / 1000000000))

# if greater than threshold, enable sleep
if [ $idle -gt $limit_s ]
then if [ $laststate = "wake" ]
then echo -n `date`
echo " sleeping disk"
pmset disksleep $limit
laststate='sleep'
fi
fi

# if less than threshold, disable sleep
if [ $idle -lt $limit_s ]
then if [ $laststate = "sleep" ]
then echo -n `date`
echo " waking disk"
pmset disksleep 0 
laststate='wake'
fi
fi

sleep 30
done
