#!/bin/sh
set -eu

# Build only the unmodified upstream tests. Resolve libyuv headers and the
# shared library from the installed packages, not from a built source tree.
# build-needed rebuilds with nocheck and therefore does not provide tests.
WORKDIR="${AUTOPKGTEST_TMP}"
GTEST_SRC_DIR=/usr/src/googletest/googletest
TEST_BINARY="${WORKDIR}/libyuv_unittest"

# Compile for the architecture under test. autopkgtest runs i386 tests on an
# amd64 testbed with i386 added as a foreign architecture; there the plain
# "c++" is the testbed's native compiler and cannot see the libyuv built for
# the architecture under test. autopkgtest exports DEB_HOST_GNU_TYPE for such
# runs; when it is unset (test architecture == testbed architecture) it is the
# native GNU type, which is what dpkg-architecture reports. This is the
# ${DEB_HOST_GNU_TYPE} compiler that the autopkgtest "Foreign architecture
# testing" documentation requires.
HOST_GNU_TYPE="${DEB_HOST_GNU_TYPE:-$(dpkg-architecture -qDEB_HOST_GNU_TYPE)}"

# libyuv0 already records a dependency on libjpeg, and the tests use libjpeg
# only through libyuv's own MJpegDecoder, so the test binary does not need to
# link libjpeg itself (there is no libjpeg dev package for the architecture
# under test in a foreign-architecture testbed).
"${HOST_GNU_TYPE}-g++" -std=c++17 -pthread -DHAVE_JPEG \
    -I"${GTEST_SRC_DIR}" -I"${GTEST_SRC_DIR}/include" \
    unit_test/*.cc "${GTEST_SRC_DIR}/src/gtest-all.cc" \
    -lyuv -o "${TEST_BINARY}"

dpkg-query -W -f='${binary:Package} ${Version}\n' libyuv0 libyuv-dev
ldd "${TEST_BINARY}" | tee "${WORKDIR}/linkage.txt"
grep -q 'libyuv\.so\.0 => /' "${WORKDIR}/linkage.txt"
"${TEST_BINARY}" --gtest_output="xml:${WORKDIR}/results.xml"
grep -Eq '<testsuites[^>]* tests="[1-9][0-9]*"' "${WORKDIR}/results.xml"
