#!/bin/sh
# Copyright 2020 Collabora Ltd.
# Copyright 2020 Simon McVittie
# SPDX-License-Identifier: BSD-3-clause

set -eux

if [ -n "${AUTOPKGTEST_ARTIFACTS-}" ]; then
    WORKDIR="$AUTOPKGTEST_ARTIFACTS"
else
    WORKDIR="$(mktemp -d)"
    trap 'cd /; rm -fr "$WORKDIR"' 0 INT QUIT ABRT PIPE TERM
fi

if [ -n "${DEB_HOST_GNU_TYPE:-}" ]; then
    CROSS_COMPILE="$DEB_HOST_GNU_TYPE-"
else
    CROSS_COMPILE=
fi

# The example programs don't include the headers in the same way that
# third-party software is expected to
for program in vorbisfile seeking; do
    sed -e 's,#include "ivorbis\(.*\)",#include <tremor/ivorbis\1>,g' \
        < "i${program}_example.c" > "$WORKDIR/$program.c"
done

cd "$WORKDIR"

for program in vorbisfile seeking; do
    # Deliberately word-splitting pkg-config's output:
    # shellcheck disable=SC2046
    "${CROSS_COMPILE}gcc" -o"$program" "$program.c" \
        $("${CROSS_COMPILE}pkg-config" --cflags --libs vorbisidec)
done

./seeking < /usr/share/sounds/freedesktop/stereo/bell.oga

./vorbisfile < /usr/share/sounds/freedesktop/stereo/bell.oga > ivorbis.raw

# Additional manual test:
#
# aplay -t raw -f S16_LE -c 2 -r 44100 "$AUTOPKGTEST_ARTIFACTS/ivorbis.raw"
# ogg123 /usr/share/sounds/freedesktop/stereo/bell.oga
#
# should sound roughly the same. They are not precisely the same due to
# different rounding(?), so we can't do a reference decode with oggdec and
# use cmp to assert they are identical.
