#!/bin/sh -e
# 
# smartmontools init.d startup script
#
# (C) 2003,04 Guido Gnther <agx@sigxcpu.org>
# 
# loosely based on the init script that comes with smartmontools which is
# copyrighted 2002 by Bruce Allen <smartmontools-support@lists.sourceforge.net>
. /lib/lsb/init-functions

[ -f /etc/default/rcS ] && . /etc/default/rcS

SMARTCTL=/usr/sbin/smartctl
SMARTD=/usr/sbin/smartd
SMARTDPID=/var/run/smartd.pid
[ -x $SMARTCTL ] || exit 0
[ -x $SMARTD ] || exit 0
RET=0

[ -r /etc/default/smartmontools ] && . /etc/default/smartmontools

smartd_opts="--pidfile $SMARTDPID $smartd_opts"

enable_smart() {
  for device in $enable_smart; do
        log_begin_msg "Enabling S.M.A.R.T. for $device"
        if [ "$VERBOSE" = "no" ]; then
                $SMARTCTL --quietmode=silent --smart=on $device || RET=2;
        else
	        $SMARTCTL --quietmode=errorsonly --smart=on $device || RET=2;
        fi
        if [ "$RET" -eq 2 ]; then
                log_end_msg 1 || true
        else
                log_end_msg 0 || true
        fi
  done
}

check_start_smartd_option() {
  if [ ! "$start_smartd" = "yes" ]; then
    [ "$VERBOSE" = "yes" ] && log_warning_msg "Not starting S.M.A.R.T. daemon smartd, disabled via /etc/default/smartmontools"
    return 1
  else
    return 0
  fi
}

case "$1" in
  start)
        [ -n "$enable_smart" ] && enable_smart
	if check_start_smartd_option; then
	    log_begin_msg "Starting S.M.A.R.T. daemon... "
            if start-stop-daemon --start --quiet --pidfile $SMARTDPID \
	    		--exec $SMARTD -- $smartd_opts; then 
	    	log_end_msg 0
	    else
                log_end_msg 1
		RET=1
	    fi
	fi
	;;
  stop)
	log_begin_msg "Stopping S.M.A.R.T. daemon... "
	start-stop-daemon --stop --quiet --oknodo --pidfile $SMARTDPID
        log_end_msg 0
	;;
  reload|force-reload)
	log_begin_msg "Reloading S.M.A.R.T. daemon..."
	if start-stop-daemon --stop --quiet --signal 1 \
			--pidfile $SMARTDPID; then
             log_end_msg 0
	else
	     log_end_msg 1
	     RET=1
	fi
  	;;
  restart)
	if check_start_smartd_option; then
	    log_begin_msg "Restarting S.M.A.R.T. daemon... "
	    start-stop-daemon --stop --quiet --oknodo --retry 30 --pidfile $SMARTDPID
            if start-stop-daemon --start --quiet --pidfile $SMARTDPID \
	    		--exec $SMARTD -- $smartd_opts; then 
                log_end_msg 0
	    else
	        log_end_msg 1
		RET=1
	    fi
	fi
        ;;
  *)
	echo "Usage: /etc/init.d/smartmontools {start|stop|restart|reload|force-reload}"
	exit 1
esac

exit $RET
