#!/usr/bin/make -f
export PYBUILD_TEST_ARGS=-k "not test_name and not test_loopback_ and not test_default_"

%:
	dh $@ --buildsystem=pybuild

override_dh_auto_test:
	@if echo " $(DEB_BUILD_OPTIONS) " | grep -q " nocheck "; then \
		echo "I: DEB_BUILD_OPTIONS contains nocheck, skipping tests"; \
		exit 0; \
	fi; \
	runtime_dir="$$(mktemp -d)"; \
	export XDG_RUNTIME_DIR="$$runtime_dir"; \
	pipewire_pid=""; \
	pipewire_pulse_pid=""; \
	cleanup() { \
		pulseaudio --kill >/dev/null 2>&1 || true; \
		[ -n "$$pipewire_pulse_pid" ] && kill "$$pipewire_pulse_pid" >/dev/null 2>&1 || true; \
		[ -n "$$pipewire_pid" ] && kill "$$pipewire_pid" >/dev/null 2>&1 || true; \
		rm -rf "$$runtime_dir"; \
	}; \
	trap cleanup EXIT INT TERM; \
	if command -v pulseaudio >/dev/null 2>&1; then \
		pulseaudio --daemonize=yes --exit-idle-time=-1 --log-target=stderr; \
	elif command -v pipewire >/dev/null 2>&1 && command -v pipewire-pulse >/dev/null 2>&1; then \
		pipewire >"$$runtime_dir/pipewire.log" 2>&1 & \
		pipewire_pid="$$!"; \
		pipewire-pulse >"$$runtime_dir/pipewire-pulse.log" 2>&1 & \
		pipewire_pulse_pid="$$!"; \
	else \
		echo "E: no supported PulseAudio server available (need pulseaudio or pipewire-pulse)"; \
		exit 1; \
	fi; \
	for _i in 1 2 3 4 5 6 7 8 9 10; do \
		if [ -S "$$XDG_RUNTIME_DIR/pulse/native" ]; then \
			break; \
		fi; \
		sleep 0.2; \
	done; \
	if [ ! -S "$$XDG_RUNTIME_DIR/pulse/native" ]; then \
		echo "E: PulseAudio socket did not appear at $$XDG_RUNTIME_DIR/pulse/native"; \
		[ -f "$$runtime_dir/pipewire.log" ] && tail -n 50 "$$runtime_dir/pipewire.log" || true; \
		[ -f "$$runtime_dir/pipewire-pulse.log" ] && tail -n 50 "$$runtime_dir/pipewire-pulse.log" || true; \
		exit 1; \
	fi; \
	echo "I: Running pybuild tests with private audio runtime at $$XDG_RUNTIME_DIR"; \
	pybuild --test --test-pytest -i python{version}
