#!/sbin/openrc-run
#
# OpenRC init script for smartmontools.
# Based on Debian's /etc/init.d/smartmontools.
#

description="SMART monitoring daemon"

command="/usr/sbin/smartd"
smartctl="/usr/sbin/smartctl"
pidfile="/var/run/smartd.pid"

extra_started_commands="reload force_reload"

depend() {
	need remote_fs
	use logger
	after rsyslog
	provide smartmontools
}

_load_defaults() {
	[ -r /etc/default/rcS ] && . /etc/default/rcS
	[ -r /etc/default/smartmontools ] && . /etc/default/smartmontools
	smartd_opts="--pidfile $pidfile ${smartd_opts:-}"
}

_enable_smart() {
	[ -n "${enable_smart:-}" ] || return 0
	local device
	ebegin "Enabling S.M.A.R.T."
	for device in $enable_smart; do
		$smartctl --quietmode=errorsonly --smart=on "$device" || true
	done
	eend 0
}

start() {
	[ -x "$command" ] || return 1
	[ -x "$smartctl" ] || return 1
	_load_defaults
	_enable_smart

	if start-stop-daemon -K -t -p "$pidfile" -x "$command" >/dev/null 2>&1; then
		einfo "${RC_SVCNAME} already running"
		return 0
	fi
	rm -f "$pidfile"
	ebegin "Starting S.M.A.R.T. daemon"
	start-stop-daemon -S -p "$pidfile" -x "$command" -- $smartd_opts
	eend $?
}

stop() {
	ebegin "Stopping S.M.A.R.T. daemon"
	start-stop-daemon -K -o -p "$pidfile"
	eend $?
}

reload() {
	ebegin "Reloading S.M.A.R.T. daemon"
	start-stop-daemon -K -s 1 -p "$pidfile"
	eend $?
}

force_reload() {
	reload
}

restart() {
	stop
	start
}
