#!/sbin/openrc-run
#
# Run anacron at boot so it can catch up with missed jobs.  Note that
# anacron is not a daemon.  It is run here just once and is later
# started by the real cron.  The cron job invokes this script again
# to keep the logic in one place.
#

description="Run anacron jobs"

# Do not reset PATH: openrc-run prepends /usr/lib/rc/bin (ebegin, mountinfo, …).

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

depend() {
	need localmount
	use logger
	after clock bootmisc
}

start() {
	[ -x /usr/sbin/anacron ] || return 0

	ebegin "Starting anac(h)ronistic cron"
	if [ "x$ANACRON_RUN_ON_BATTERY_POWER" != "xyes" ] && [ -x /usr/bin/on_ac_power ]
	then
		/usr/bin/on_ac_power >/dev/null
		if [ $? -eq 1 ]
		then
			ewarn "deferred while on battery power"
			eend 0
			return 0
		fi
	fi

	# on_ac_power doesn't exist, on_ac_power returns 0 (AC power),
	# or on_ac_power returns 255 (undefined, desktop without APM)
	start-stop-daemon --start --exec /usr/sbin/anacron -- $ANACRON_ARGS
	eend 0
}

stop() {
	ebegin "Stopping anac(h)ronistic cron"
	# Double --quiet suppresses "no matching processes" (oneshot often already exited).
	# Avoid --oknodo (deprecated in OpenRC's start-stop-daemon).
	start-stop-daemon --stop --quiet --quiet --exec /usr/sbin/anacron \
		--retry=USR1/90/TERM/5/KILL/5
	RETVAL=$?
	case "$RETVAL" in
		0|1) eend 0 ;;
		*)   eend 1 ;;
	esac
}

reload() {
	:
}

restart() {
	:
}
