#!/bin/sh
# Spend this session's first PipeWire playback start on nothing.
#
# The audio DSP swallows one VBC scene start per boot: the driver sends it, the
# send succeeds, but nothing ever drains the VBC fifo, so the writer either gets
# -EIO or blocks forever having moved no audio. The start that goes missing is
# the one PipeWire issues when it resumes the sink - opening hw:0,3 directly,
# outside PipeWire, is a different start and does not stand in for it. So
# whatever the user plays first loses it and the board looks silent.
#
# Opening pavucontrol "fixes" it, which is how this was found: it plays nothing,
# but its level-meter monitor streams resume the sink, and it neither notices nor
# cares that the resume went nowhere. Do that deliberately instead, once, with
# silence. Suspend behaviour is left alone so the sink can still be resumed again
# if this ever runs at the wrong moment.
set -u
PATH=/usr/bin:/usr/sbin:/bin:/sbin
export PATH

command -v pw-cat >/dev/null 2>&1 || exit 0

# Retry until one playback completes on its own. There is nothing worth polling -
# pw-cat cannot be asked whether the sink exists - and both failure shapes end an
# attempt anyway: a fast error means no sink yet, and the lost start wedges the
# writer rather than failing it, which is what the timeout's -k is for. Either way
# the bad start is spent. Keep the deadline inside the unit's TimeoutStartSec.
deadline=$(($(date +%s) + 15))
while [ "$(date +%s)" -lt "$deadline" ]; do
	dd if=/dev/zero bs=4096 count=48 2>/dev/null |
		timeout -k 2 5 pw-cat --playback --format=s16 --rate=48000 \
			--channels=2 --raw - >/dev/null 2>&1 && exit 0
	sleep 0.5
done

exit 0
