#!/bin/sh
# description: Setup auto spindown.
# chkconfig: - 00 99
# conifg: /etc/hddspin

# Source function library.
if [ -f /etc/init.d/functions ] ; then
  . /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
  . /etc/rc.d/init.d/functions
else
  exit 0
fi

# Avoid using root's TMPDIR
unset TMPDIR

# default setting in /etc/hddspin
# 2 min. to spin down. (24 x 5) seconds.
SPINDOWN_TIME=24

# Advanced power management level
APM_LEVEL=1

# devices to spin down.
SPINDOWN_DEVICE=

# device which is mounted on /.
ROOT_DEVICE=`mount | grep "on / " | cut -f1 -d" " | sed -e 's/[0-9]$//' | sed -e 's!/dev/!!'`

# RESTRICTION: only one cdrom device in system.
CDROM_DEVICE=
pwd_save=`pwd`
cd /dev
if [ -h cdrom ]
then
	CDROM_DEVICE=`stat -c '%N' cdrom | cut -f 3 -d $'\140' | cut -f 1 -d "'" `
fi

if [ "X${CDROM_DEVICE}" != "X" ]
then
	SPINDOWN_DEVICE=(`ls sd[a-z] hd[a-z] | grep -v ${CDROM_DEVICE} | grep -v ${ROOT_DEVICE}`)
else
	SPINDOWN_DEVICE=(`ls sd[a-z] hd[a-z] | grep -v ${ROOT_DEVICE}`)
fi
cd ${pwd_save}

# devices to do aggressive Advanced power management.
APM_DEVICE=( ${ROOT_DEVICE[*]} ${SPINDOWN_DEVICE[*]})

# Source Hdd spin down configuration
if [ -f /etc/hddspin ]
then
	source /etc/hddspin
fi

RETVAL=0


start() {
	for disk in ${APM_DEVICE[*]}
	do
		/sbin/hdparm -B ${APM_LEVEL} /dev/${disk}
	done
	for disk in ${SPINDOWN_DEVICE[*]}
	do
		/sbin/hdparm -S ${SPINDOWN_TIME} /dev/${disk}
	done
        return 0
}

stop() {
	# do nothing
	return 0
}

restart() {
        stop
        start
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        restart
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart}"
        exit 1
esac

exit $?
