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

set -e
set -u
set -x

# Test that we can compile a simple project using meson and ninja.

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=
arch="$(dpkg --print-architecture)"

for compiler in \
    '' \
    binutils-2.35 \
    clang \
    clang-9 \
    clang-11 \
    clang-13 \
    gcc \
    gcc-9 \
    gcc-10 \
    gcc-14 \
    gcc-14/mold \
; do
    n=$((n + 1))
    linker=

    case "$arch:$compiler" in
        (i386:gcc-14*)
            echo "ok $n - $compiler # SKIP not supported on i386"
            continue
            ;;
    esac

    case "$compiler" in
        ('' | clang | clang-11 | gcc | gcc-10)
            # default version, guaranteed to be present in SDK
            ;;

        (gcc-14)
            # backport, explicitly included in SDK
            ;;

        (gcc-14/mold)
            compiler=gcc-14
            linker=mold
            ;;

        (binutils-2.35)
            # explicitly included in SDK
            compiler=
            linker=binutils-2.35
            ;;

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

    if \
        meson setup \
            ${compiler:+--native-file "${compiler}.txt"} \
            ${linker:+--native-file "${linker}.txt"} \
            "$tmpdir/b" \
            "$(pwd)/examples/glib" \
        && ninja -v -C "$tmpdir/b" \
        && ./tests/assert-correct-ldso.sh "$(dpkg --print-architecture)" "$tmpdir/b/hello" \
        && "$tmpdir/b/hello" \
    ; then
        echo "ok $n - ${compiler:-default}"
    else
        echo "not ok $n - ${compiler:-default}"
        failed=1
    fi

    if [ "$linker" = "mold" ]; then
        n=$((n + 1))

        if strings "$tmpdir/b/hello" | grep '^mold [0-9]' >&2; then
            echo "ok $n - $tmpdir/b/hello was linked with mold"
        else
            echo "not ok $n - $tmpdir/b/hello not linked with mold"
            failed=1
        fi
    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:
