#!/bin/bash
# autopkgtest for the Debian vmpk package: headless smoke test.
#
# Runs vmpk with QT_QPA_PLATFORM=offscreen inside a private D-Bus
# session bus and verifies that it:
#   1. starts up and registers the D-Bus name "net.sourceforge.vmpk",
#   2. exposes the expected D-Bus MIDI methods (noteon/noteoff) and
#      signals (event_noteon/event_noteoff), and method invocations
#      succeed,
#   3. processes a real MIDI event fed in through the drumstick-rt
#      "Network" backend (UDP multicast) and re-emits it as the
#      corresponding D-Bus signal,
#   4. exits cleanly (status 0) on the D-Bus quit() request.
#
# The drumstick Network input is preselected in the seeded QSettings
# profile because a podman testbed has no /dev/snd for the ALSA one.
#
# AI assisted code, reviewed and tested by snd@debian.org

set -eu

WORKDIR=${AUTOPKGTEST_TMP:-$(mktemp -d)}
mkdir -p "$WORKDIR"
export AUTOPKGTEST_TMP="$WORKDIR"

TESTDIR=$(cd "$(dirname "$0")" && pwd)

BUS_NAME=net.sourceforge.vmpk
IFACE=$BUS_NAME

# drumstick-rt Network backend defaults: multicast group 225.0.0.37,
# ports 21928..21947.  With a fresh profile vmpk opens the first
# connection in the backend's list, i.e. UDP port 21928.
MIDI_GROUP=225.0.0.37
MIDI_PORT=21928
NOTE=60

WAIT_SERVICE=30	# seconds until the D-Bus name must appear
WAIT_SIGNAL=20	# seconds until each MIDI event signal must appear
WAIT_EXIT=15	# seconds to exit after quit()

APP_PID=
MONITOR_PID=

log() {
	printf '[%s] %s\n' "$(date +%H:%M:%S)" "$*" >&2
}

dump_logs() {
	local f
	for f in "$WORKDIR/app.log" "$WORKDIR/monitor.log" "$WORKDIR/bus.err"; do
		if [ -s "$f" ]; then
			log "--- $f ---"
			sed -e 's/^/  /' "$f" >&2
			log "--- end of $f ---"
		fi
	done
}

fail() {
	log "FAILED: $*"
	dump_logs
	exit 1
}

cleanup() {
	set +e
	if [ -n "$MONITOR_PID" ]; then
		kill "$MONITOR_PID" 2>/dev/null
		wait "$MONITOR_PID" 2>/dev/null
	fi
	if [ -n "$APP_PID" ]; then
		is_alive "$APP_PID" && kill "$APP_PID" 2>/dev/null
		wait "$APP_PID" 2>/dev/null
	fi
}

# is_alive: 0 if the process still exists as a running process, 1 if it
# has exited (zombie or gone).  Calling jobs(1) first reaps any exited
# background children, which keeps this portable to testbeds without a
# mounted /proc (and to zombies, which kill -0 alone would still see).
is_alive() {
	jobs >/dev/null 2>&1
	kill -0 "$1" 2>/dev/null
}

dbus_name_registered() {
	dbus-send --session --print-reply \
		--dest=org.freedesktop.DBus / org.freedesktop.DBus.ListNames \
		2>/dev/null | grep -q "\"$BUS_NAME\""
}

dbus_call() {
	# The vmpk D-Bus methods carry the NoReply annotation, but the
	# generated Qt adaptor still sends an empty method return, so
	# --print-reply fails fast on unknown interfaces/members.
	dbus-send --session --type=method_call --print-reply \
		--dest="$BUS_NAME" / "$IFACE.$1" "${@:2}" \
		>/dev/null 2>"$WORKDIR/dbus.err"
}

# send_midi <hex bytes>: inject a raw MIDI message through the
# drumstick-rt Network backend using the shell's UDP redirection.
send_midi() {
	printf "$1" > "/dev/udp/$MIDI_GROUP/$MIDI_PORT"
}

# expect_signal <member> [send-command...]: wait for a D-Bus signal,
# optionally re-sending a message every second until it is observed.
expect_signal() {
	local sig=$1 n=0
	shift
	until grep -q "member=$sig" "$WORKDIR/monitor.log" 2>/dev/null; do
		is_alive "$APP_PID" || fail "vmpk exited before emitting the D-Bus signal $sig"
		n=$((n + 1))
		[ "$n" -lt $((WAIT_SIGNAL * 10)) ] || fail "the D-Bus signal $sig was not observed within ${WAIT_SIGNAL}s"
		if [ "$#" -gt 0 ]; then
			"$@"
		fi
		sleep 0.1
	done
	log "observed D-Bus signal: $sig"
}

if [ "${VMPK_SMOKE_INNER:-}" != 1 ]; then
	export HOME="$WORKDIR/home"
	export XDG_CONFIG_HOME="$WORKDIR/config"
	export XDG_CACHE_HOME="$WORKDIR/cache"
	export XDG_RUNTIME_DIR="$WORKDIR/runtime"
	mkdir -p "$HOME" "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME" "$XDG_RUNTIME_DIR" \
		"$HOME/.config/vmpk.sourceforge.net"
	chmod 700 "$XDG_RUNTIME_DIR"
	export LC_ALL=C.UTF-8
	export QT_QPA_PLATFORM=offscreen

	# Seed the QSettings profile so that the drumstick-rt Network
	# backend is used for MIDI input.  This backend is available in
	# libdrumstick-rt-backends on every testbed and needs no hardware.
	printf '[Connections]\nInputDriver=Network\n' \
		> "$HOME/.config/vmpk.sourceforge.net/VMPK.conf"

	log "temporary state directory: $WORKDIR"
	log "starting private D-Bus session bus (dbus-run-session)"
	exec dbus-run-session -- env VMPK_SMOKE_INNER=1 "$TESTDIR/smoke"
fi

trap cleanup EXIT INT TERM

log "watching for D-Bus signals emitted by vmpk (dbus-monitor)"
stdbuf -oL dbus-monitor --session \
	"type='signal',interface='$IFACE'" \
	>"$WORKDIR/monitor.log" 2>"$WORKDIR/bus.err" &
MONITOR_PID=$!

log "starting vmpk with the Qt offscreen platform (headless)"
vmpk >"$WORKDIR/app.log" 2>&1 &
APP_PID=$!

n=0
until dbus_name_registered; do
	is_alive "$APP_PID" || fail "vmpk terminated during startup (it needs a usable drumstick-rt MIDI output backend)"
	n=$((n + 1))
	[ "$n" -lt $((WAIT_SERVICE * 10)) ] || fail "vmpk did not register the D-Bus name $BUS_NAME within ${WAIT_SERVICE}s"
	sleep 0.1
done
log "vmpk is running and has registered the D-Bus name $BUS_NAME"

log "checking the generated D-Bus interface through introspection"
dbus-send --session --print-reply \
	--dest="$BUS_NAME" / org.freedesktop.DBus.Introspectable.Introspect \
	>"$WORKDIR/introspect.log" 2>&1 \
	|| fail "cannot introspect the vmpk D-Bus object"
grep -q "<method name=\"noteon\">" "$WORKDIR/introspect.log" \
	|| fail "the D-Bus interface is missing the noteon method"
grep -q "<signal name=\"event_noteon\">" "$WORKDIR/introspect.log" \
	|| fail "the D-Bus interface is missing the event_noteon signal"
log "D-Bus interface exposes noteon and event_noteon"

log "invoking D-Bus MIDI methods directly (noteon/noteoff/octave)"
dbus_call noteon "int32:$NOTE" || fail "D-Bus method call noteon failed"
dbus_call noteoff "int32:$NOTE" || fail "D-Bus method call noteoff failed"
dbus_call octave "int32:-1" || fail "D-Bus method call octave failed"
log "D-Bus method calls succeeded"

log "feeding a real MIDI note-on event through the drumstick-rt Network backend"
expect_signal event_noteon send_midi '\x90\x3c\x40'
log "feeding a real MIDI note-off event"
expect_signal event_noteoff send_midi '\x80\x3c\x00'

if ! grep -q "int32 $NOTE" "$WORKDIR/monitor.log" 2>/dev/null; then
	fail "the observed D-Bus signals do not carry the expected note payload ($NOTE)"
fi
log "the MIDI event pipeline works end-to-end (UDP -> drumstick-rt -> vmpk -> D-Bus)"

log "asking vmpk to quit through D-Bus"
dbus-send --session --type=method_call --dest="$BUS_NAME" / "$IFACE.quit" \
	>/dev/null 2>&1
n=0
while is_alive "$APP_PID"; do
	n=$((n + 1))
	[ "$n" -lt $((WAIT_EXIT * 10)) ] || fail "vmpk did not exit within ${WAIT_EXIT}s after the D-Bus quit() request"
	sleep 0.1
done

rc=0
wait "$APP_PID" 2>/dev/null || rc=$?
if [ "$rc" -ne 0 ]; then
	fail "vmpk exited with status $rc after quit()"
fi
log "vmpk exited cleanly (status 0)"

log "ALL CHECKS PASSED"
