#!/bin/sh
# Render a module with headless WAV export and inspect the resulting audio.
# This exercises the module loader, the playback engine, and the WAV writer
# without needing a display or an audio device.
#
# AI-assisted code, reviewed and tested by snd@debian.org.

set -eu
# AI-assisted code, reviewed and tested by snd@debian.org.
testdir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT HUP INT TERM

# Keep the test out of the user's real configuration directory.
export HOME="$work/home"
export XDG_CACHE_HOME="$HOME/.cache"
export XDG_CONFIG_HOME="$HOME/.config"
export XDG_DATA_HOME="$HOME/.local/share"
export XDG_STATE_HOME="$HOME/.local/state"
mkdir -p "$HOME"

fail() {
    echo "FAIL: $*" >&2
    exit 1
}

echo "== creating a test module =="
python3 "$testdir/data/make-test-mod.py" "$work/test.mod"

echo "== rendering the module to WAV =="
schismtracker --headless --diskwrite="$work/out.wav" "$work/test.mod"
[ -s "$work/out.wav" ] || fail "schismtracker did not create a WAV file"

echo "== checking the rendered audio =="
python3 "$testdir/data/check-wav.py" "$work/out.wav"

# Rendering the same module twice must produce identical output.  Apart from
# being a useful determinism check, this ensures that a previous run is not
# silently reusing stale state.
echo "== checking that rendering is deterministic =="
schismtracker --headless --diskwrite="$work/out-again.wav" "$work/test.mod"
cmp "$work/out.wav" "$work/out-again.wav"

echo "PASS: headless module rendering"
