#!/sbin/openrc-run
#
# OpenRC init script for apcupsd UPS power management.
#

description="UPS power management"

CONFIG=/etc/default/apcupsd
DAEMON=/usr/sbin/apcupsd
PIDFILE=/var/run/apcupsd.pid
APCACCESS=/usr/sbin/apcaccess

depend() {
	need localmount
	use logger
	after bootmisc
}

configured() {
	[ -x "$DAEMON" ] || return 1
	[ -e "$CONFIG" ] || return 1
	# shellcheck disable=SC1090
	. "$CONFIG"
	[ "x$ISCONFIGURED" = "xyes" ]
}

start_pre() {
	configured || return 0
	/usr/lib/apcupsd/prestart || return 1
	if pidof apcupsd >/dev/null 2>&1; then
		ewarn "A copy of the daemon is still running"
		return 0
	fi
	return 0
}

start() {
	configured || return 0

	ebegin "Starting apcupsd"
	start-stop-daemon --start --quiet --exec "$DAEMON"
	eend $?
}

stop() {
	ebegin "Stopping apcupsd"
	start-stop-daemon --stop --quiet --quiet --exec "$DAEMON" --pidfile "$PIDFILE" || true
	rm -f "$PIDFILE"
	eend 0
}

status() {
	"$APCACCESS" status
}

restart() {
	stop
	sleep 10
	start
}
