#!/usr/bin/bash
set -euo pipefail

state_dir=${NABU_SLPI_STATE_DIR:-/run/nabu-slpi-suspend}
iio_marker=${state_dir}/iio-sensor-proxy.was-active
sdsp_marker=${state_dir}/hexagonrpcd-sdsp.was-active
adsp_marker=${state_dir}/hexagonrpcd-adsp-rootpd.was-active

record_and_stop() {
	local unit=$1
	local marker=$2

	if systemctl is-active --quiet "${unit}"; then
		install -Dm0644 /dev/null "${marker}"
		systemctl stop "${unit}"
	fi
}

start_if_recorded() {
	local unit=$1
	local marker=$2

	if [[ -e ${marker} ]]; then
		systemctl start "${unit}"
		unlink "${marker}"
	fi
}

case ${1:-} in
	prepare)
		install -d -m0755 "${state_dir}"
		# /run is cleared at boot.  Keep markers created by an interrupted
		# resume so a later cycle still restores every previously active client.
		record_and_stop iio-sensor-proxy.service "${iio_marker}"
		record_and_stop hexagonrpcd-sdsp.service "${sdsp_marker}"
		record_and_stop hexagonrpcd-adsp-rootpd.service "${adsp_marker}"
		! systemctl is-active --quiet iio-sensor-proxy.service
		! systemctl is-active --quiet hexagonrpcd-sdsp.service
		! systemctl is-active --quiet hexagonrpcd-adsp-rootpd.service
		;;
	resume)
		start_if_recorded hexagonrpcd-adsp-rootpd.service "${adsp_marker}"
		start_if_recorded hexagonrpcd-sdsp.service "${sdsp_marker}"
		start_if_recorded iio-sensor-proxy.service "${iio_marker}"
		;;
	*)
		echo "Usage: $0 {prepare|resume}" >&2
		exit 64
		;;
esac
