#!/bin/sh
#
# spindown     Start/Stop the spindown clock daemon
#
# chkconfig:   - 90 60
# description: Daemon that can spindown idle disks

### BEGIN INIT INFO
# Short-Description: Daemon that can spin idle disks down 
# Description:       Spindown is a daemon that can spin idle disks down and thus save energy and 
#                    improve disk lifetime. It periodically checks for read or written blocks. When
#                    no blocks are read or written the disk is idle. When a disk stays idle long
#                    enough, spindown uses custom command like sg_start or hdparm to spin it down.
#                    It also works with USB disks and hot-swappable disks because it doesn't watch
#                    the device name (hda, sdb, ...), but the device ID. This means that it doesn't
#                    matter if the disk is swapped while the daemon is running.
### END INIT INFO

[ -f /etc/sysconfig/crond ] || { 
    [ "$1" = "status" ] && exit 4 || exit 6 
}

prog="spindownd"
exec="/usr/sbin/spindownd"
lockfile="/var/lock/subsys/spindown"
pidfile="/var/run/spindownd.pid"
config="/etc/spindown.conf"
statuspipe="/var/run/spindown.status"

# Source function library.
. /etc/rc.d/init.d/functions

[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog

start() {
    [ $UID -eq 0 ] || exit 4
    [ -x $exec ] || exit 5
    [ -f $config ] || exit 6
    echo -n $"Starting $prog: "
    daemon $exec -d -f $statuspipe -c $config -p $pidfile; 
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc -p /var/run/spindownd.pid $exec
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

printstatus()
{
    printf "%-5s %10s %10s %15s %20s\n" name watched active idle-time spindown-time
    while read line; do
            printf "%-5s %10s %10s %15s %20s\n" $line
    done < $statuspipe
    exit 0
}

restart() {
    stop
    start
}

reload() {
    echo -n $"Reloading $prog: "
    killproc -p $pidfile $exec -HUP
    echo
}

force_reload() {
    reload 
}

rh_status() {
    if [ -p $statuspipe ]; then
            printstatus &
            sleep 0.5
            kill -pipe `cat $pidfile`
            wait $!
    fi
    status -p $pidfile $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}


case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
        restart
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
        exit 2
esac
exit $?

