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

set -e
set -u
set -x

# Test that we can compile a simple C project using make and a
# compiler that targets the host architecture.

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

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

cp -a examples/glib/* "$tmpdir"

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)
PKG_CONFIG="${gnu_tuple}-pkgconf"

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

    case "$compiler" in
        (gcc | gcc-*)
            CC="${gnu_tuple}-${compiler}"
            CXX="${gnu_tuple}-g++${compiler#gcc}"
            ;;

        (clang | clang-*)
            CC="$compiler --target=${gnu_tuple}"
            CXX="clang++${compiler#clang} --target=${gnu_tuple}"
            ;;

        (*)
            echo "internal error: unrecognized compiler" >&2
            exit 2
            ;;
    esac

    make -C "$tmpdir" V=1 CC="$CC" CXX="$CXX" PKG_CONFIG="$PKG_CONFIG"
    file "$tmpdir/hello"
    ./tests/assert-correct-ldso.sh "$DEB_HOST_ARCH" "$tmpdir/hello"

    case "$DEB_BUILD_ARCH/$DEB_HOST_ARCH" in
        (amd64/i386)
            "$tmpdir/hello"
            ;;
    esac

    make -C "$tmpdir" V=1 CC="$CC" CXX="$CXX" PKG_CONFIG="$PKG_CONFIG" clean

    echo "ok $n - $CC"
done

echo "1..$n"

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

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