#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Runs feature sleep/resume hooks. The T2 NCM link now survives suspend on
# its own (t2bce_vhci reset-resumes it after a stateful sleep), so this no
# longer needs to unbind/rebind cdc_ncm or wait for the link to come back.
set -uo pipefail
HOOK_DIR=${T2_HOOK_DIR:-"$(dirname -- "$0")/sleep.d"}
errors=()

log_error() {
	printf '[t2-services] error: %s\n' "$*" >&2
	errors+=("$*")
}

run_hooks() {
	local hook
	for hook in "$HOOK_DIR"/*; do
		[[ -x "$hook" && -f "$hook" ]] || continue
		if ! timeout --kill-after=2 125 "$hook" "$1"; then
			log_error "${hook##*/} $1 failed; continuing"
		fi
	done
}

case "${1:-}" in
	pre) run_hooks pre ;;
	post) run_hooks post ;;
	*) printf 'usage: %s pre|post\n' "$0" >&2; exit 2 ;;
esac
if (( ${#errors[@]} )); then
	printf '[t2-services] sleep transition completed with %s error(s):\n' "${#errors[@]}" >&2
	printf '  %s\n' "${errors[@]}" >&2
fi
# Never prevent system sleep/resume because an individual device failed.
exit 0
