#!/bin/bash
# Copyright © 2019-2025 Collabora Ltd.
# SPDX-License-Identifier: BSD-3-Clause
# (See debian/copyright)

set -e
set -u
set -x

case "$(dpkg --print-architecture)" in
    (amd64|i386)
        ;;
    (*)
        echo "1..0 # SKIP - not x86"
        exit 0
        ;;
esac

# Test that we can compile a simple project using CMake.

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

n=0
failed=

gcc_major=$(gcc -dumpversion)

for cc in \
    gcc \
    "gcc-${gcc_major}" \
; do
    n=$((n + 1))
    cxx="g++${cc#gcc}"

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

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

    if \
        mkdir "$tmpdir/b" \
        && \
            CFLAGS=-m32 \
            CXXFLAGS=-m32 \
            CC="${cc}" \
            CXX="${cxx}" \
            PKG_CONFIG="i686-linux-gnu-pkg-config" \
            cmake -S "$(pwd)/examples/glib" -B "$tmpdir/b" \
        && make -C "$tmpdir/b" \
        && grep -F /lib/ld-linux.so.2 "$tmpdir/b/hello" \
        && "$tmpdir/b/hello" \
    ; then
        echo "ok $n - ${cc}/${cxx} with environment variables"
    else
        echo "not ok $n - ${cc}/${cxx} with environment variables"
        failed=1
    fi

    make -C "$tmpdir/b" clean
    rm -fr "$tmpdir/b"
    n=$((n + 1))

    toolchain="/usr/share/steamrt/cmake/${cc}-m32.cmake"

    # Check that CFLAGS, CXXFLAGS from the environment don't remove -m32
    if \
        mkdir "$tmpdir/b" \
        && \
            CFLAGS=-O1 \
            CXXFLAGS=-O1 \
            cmake \
                -S "$(pwd)/examples/glib" \
                -B "$tmpdir/b" \
                -DCMAKE_TOOLCHAIN_FILE="$toolchain" \
                -GNinja \
        && ninja -v -C "$tmpdir/b" \
        && grep -F /lib/ld-linux.so.2 "$tmpdir/b/hello" \
        && "$tmpdir/b/hello" \
    ; then
        echo "ok $n - ${cc}/${cxx} with toolchain file"
    else
        echo "not ok $n - ${cc}/${cxx} with toolchain file"
        failed=1
    fi

    ninja -v -C "$tmpdir/b" clean
    rm -fr "$tmpdir/b"
done

echo "1..$n"

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

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