#!/bin/bash
# Copyright © 2019-2026 Collabora Ltd.
# SPDX-License-Identifier: BSD-3-Clause

set -e
set -u
set -x

# Test that we can cross-compile a SDL3 project using meson and ninja.

if [ -z "${DEB_HOST_ARCH-}" ] || [ "$DEB_HOST_ARCH" = "${DEB_BUILD_ARCH-}" ]; then
    echo "1..0 # SKIP DEB_HOST_ARCH not configured"
    exit 0
fi

if [ "${DEB_HOST_ARCH}" = i386 ]; then
    echo "1..0 # SKIP SDL3 satellite libraries not currently supported on i386"
    exit 0
fi

tmpdir="$(mktemp -d)"
cleanup () {
    rm -fr "$tmpdir"
}
trap cleanup 0 INT QUIT ABRT PIPE TERM

# Meson wants a real locale
export LC_ALL=C.UTF-8

n=0
failed=

gnu_tuple="$(dpkg-architecture -a"$DEB_HOST_ARCH" -qDEB_HOST_GNU_TYPE 2>/dev/null)"
gcc_major=$(gcc -dumpversion)
clang_major=$(clang -dumpversion | cut -d. -f1)

for compiler in \
    clang \
    "clang-${clang_major}" \
    gcc \
    "gcc-${gcc_major}" \
; do
    n=$((n + 1))

    case "$compiler" in
        (clang | "clang-${clang_major}" | gcc | "gcc-${gcc_major}")
            # default version, guaranteed to be present in SDK
            ;;

        (gcc*)
            if ! command -v "${gnu_tuple}-$compiler" >/dev/null; then
                echo "ok $n # SKIP ${gnu_tuple}-$compiler not in PATH"
                continue
            fi
            ;;

        (clang*)
            if ! command -v "$compiler" >/dev/null; then
                echo "ok $n # SKIP $compiler not in PATH"
                continue
            fi
            ;;
    esac

    if \
        meson setup \
            --cross-file "${gnu_tuple}-${compiler}.txt" \
            "$tmpdir/b" \
            "$(pwd)/examples/sdl3" \
        && ninja -v -C "$tmpdir/b" \
        && ./tests/assert-correct-ldso.sh "$DEB_HOST_ARCH" \
            "$tmpdir/b/hello" \
            "$tmpdir/b/showfont" \
            "$tmpdir/b/showimage" \
    ; then
        echo "ok $n - $compiler"

        ninja -v -C "$tmpdir/b" clean
    else
        echo "not ok $n - $compiler"
        failed=1
    fi

    rm -fr "$tmpdir/b"
done

echo "1..$n"

if [ -n "$failed" ]; then
    exit 1
fi

# vim:set sw=4 sts=4 et ft=sh:
