#!/bin/bash
# Copyright © 2019 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 i386.

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

n=0
failed=

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

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

gnu_tuple="$(dpkg-architecture -ai386 -qDEB_HOST_GNU_TYPE 2>/dev/null)"
gcc_major=$(gcc -dumpversion)
clang_major=$(clang -dumpversion | cut -d. -f1)
PKG_CONFIG="${gnu_tuple}-pkg-config"

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"
    grep -F /lib/ld-linux.so.2 "$tmpdir/hello"
    "$tmpdir/hello"
    make -C "$tmpdir" V=1 CC="$CC" CXX="$CXX" PKG_CONFIG="$PKG_CONFIG" clean

    echo "ok $n - $CXX"
done

echo "1..$n"

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

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