#!/bin/sh
set -e

# Created with some help of AI. The code has been reviewed and very well tested.

export LC_ALL=C
export LADSPA_PATH=/usr/lib/ladspa
export LV2_PATH=/usr/lib/lv2

workdir=$(mktemp -d)
trap 'rm -rf "$workdir"' EXIT

# 1) LV2: load every zam-plugins LV2 plugin and run it on real audio
for uri in $(lv2ls | grep -E '^urn:zamaudio:'); do
    name=$(echo "$uri" | sed 's/.*://')
    # Count audio input ports (including sidechains) so we can feed enough channels
    ain=$(lv2file -n "$uri" 2>/dev/null | sed -n '/==Audio Ports==/,/==Control Ports==/p' | grep -c ':' || true)
    if [ -z "$ain" ] || [ "$ain" -lt 1 ]; then
        echo "Cannot determine audio input port count for $uri" >&2
        exit 1
    fi
    ffmpeg -y -v error -f lavfi -i sine=frequency=440:duration=0.1 \
        -ar 48000 -ac "$ain" "$workdir/in-$name.wav"
    lv2file -i "$workdir/in-$name.wav" -o "$workdir/out-$name.wav" "$uri" --ignore-clipping
    # Verify the output is a decodable WAV file
    ffmpeg -v error -i "$workdir/out-$name.wav" -f null -
done

# 2) LADSPA: run every zam-plugins LADSPA plugin on real audio
for so in /usr/lib/ladspa/Za*-ladspa.so; do
    label=$(analyseplugin "$so" | awk -F'"' '/Plugin Label/ {print $2}')
    vals=$(analyseplugin "$so" | grep 'input, control' | \
        sed -n 's/.*default \([0-9.-]*\).*/\1/p')
    ain=$(analyseplugin "$so" | grep -c 'input, audio')
    ffmpeg -y -v error -f lavfi -i sine=frequency=440:duration=0.1 \
        -ar 48000 -ac "$ain" "$workdir/in-ladspa.wav"
    applyplugin "$workdir/in-ladspa.wav" "$workdir/out-ladspa.wav" "$so" "$label" $vals
    ffmpeg -v error -i "$workdir/out-ladspa.wav" -f null -
done

# 3) Runtime dependency sanity check for all plugin binaries
for so in /usr/lib/lv2/*/*.so \
          /usr/lib/clap/*.clap \
          /usr/lib/ladspa/Za*-ladspa.so; do
    [ -f "$so" ] || continue
    if ldd "$so" | grep -q 'not found'; then
        echo "Missing shared library dependency in $so" >&2
        ldd "$so"
        exit 1
    fi
done

for so in $(find /usr/lib/vst3 -name '*.so' 2>/dev/null); do
    if ldd "$so" | grep -q 'not found'; then
        echo "Missing shared library dependency in $so" >&2
        ldd "$so"
        exit 1
    fi
done
