#!/sbin/openrc-run
# SPDX-License-Identifier: MIT

description="Firmware update daemon interfaced with hawkbit"

command="/usr/bin/swupdate"
pidfile="/run/swupdate_hawkbit.pid"

# options (set variables in /etc/conf.d/swupdate-hawkbit)
# suricatta_args: options for the suricatta part of swupdate command (within -u)
# swupdate_args: other options
#
# In most case the variables should not be needed, and configuration should
# be placed in /etc/swupdate.conf instead.

depend() {
	need localmount net
	after network-online
}

error() {
	eend 1 "$@"
	exit 1
}

start() {
	local hawkbit_confirm=0 TMPDIR

	ebegin "Starting swupdate hawkbit daemon"

	if [ -e "/var/log/swupdate/hawkbit_install_done" ]; then
		if abos-ctrl status -q; then
			hawkbit_confirm=2
		else
			hawkbit_confirm=3
		fi
		# XXX this should normally only be removed after communication with
		# hawkbit server has been verified, but we have no way of doing that
		rm -f "/var/log/swupdate/hawkbit_install_done"
	fi

	TMPDIR=$(mktemp -d /var/tmp/swupdate-hawkbit.XXXXXX) || error "Could not create temp dir"
	echo "$TMPDIR" > /run/swupdate_hawkbit.tmpdir
	# shellcheck disable=SC2086 # expand swupdate_args on purpose
	start-stop-daemon --start --quiet --exec "${command}" \
		--background --make-pidfile --pidfile="$pidfile" \
		-e "TMPDIR=$TMPDIR" -e "SWUPDATE_HAWKBIT=1" \
		-- -u "-e -c ${hawkbit_confirm} ${suricatta_args-}" ${swupdate_args-}

	eend $? "Could not start swupdate hawkbit daemon"
}

stop() {
	local TMPDIR

	ebegin "Stopping swupdate hawkbit daemon"

	start-stop-daemon --stop --pidfile="$pidfile"

	if [ -e "/run/swupdate_hawkbit.tmpdir" ]; then
		TMPDIR=$(cat /run/swupdate_hawkbit.tmpdir)
		find "$TMPDIR" /run/swupdate_hawkbit.tmpdir -xdev -delete 2>/dev/null
	fi

	eend 0
}
