#!/bin/sh
# Exercise libtinyalsa, the tinyalsa utilities and the upstream gtest suite
# against snd-aloop virtual sound cards.
#
# The upstream test suite expects cards 0..2 to exist (mixer tests iterate
# over them, PCM tests assume hw:0,0 is usable) and card 2 to be a snd-aloop
# loopback card (playback on device 0, capture on device 1). Any of those
# cards that does not exist yet is created as a snd-aloop instance.
set -eu

skip() {
    echo "SKIP: $*" >&2
    exit 77
}

LOOPBACK_CARD=2

if [ -e "/proc/asound/card$LOOPBACK_CARD" ]; then
    grep -q '^Loopback$' "/proc/asound/card$LOOPBACK_CARD/id" \
        || skip "card $LOOPBACK_CARD exists but is not a snd-aloop card"
else
    if [ -d /sys/module/snd_aloop ]; then
        skip "snd-aloop is already loaded without a card at index $LOOPBACK_CARD"
    fi
    enable=
    index=
    for i in 0 1 2; do
        if [ ! -e "/proc/asound/card$i" ]; then
            enable="${enable:+$enable,}1"
            index="${index:+$index,}$i"
        fi
    done
    echo "Loading snd-aloop for card indices $index"
    modprobe snd-aloop enable="$enable" index="$index" \
        || skip "cannot load the snd-aloop kernel module"
fi

for i in 0 1 2; do
    [ -e "/proc/asound/card$i" ] || skip "card $i is missing"
done
cat /proc/asound/cards

# Wait for udev to create the device nodes.
for _ in $(seq 1 30); do
    [ -e "/dev/snd/pcmC${LOOPBACK_CARD}D0p" ] && [ -e "/dev/snd/pcmC${LOOPBACK_CARD}D1c" ] && break
    sleep 1
done
ls -l /dev/snd/

echo "### tinypcminfo"
tinypcminfo -D "$LOOPBACK_CARD" -d 0

echo "### tinymix"
tinymix -D "$LOOPBACK_CARD" controls
tinymix -D "$LOOPBACK_CARD" contents

echo "### upstream gtest suite"
/usr/libexec/tinyalsa/tinyalsa_test
