#!/bin/sh
set -C -e -f -u
cd "$AUTOPKGTEST_TMP"

gcc_major=$(gcc -dumpversion)
gnat_major=$(gnatmake --version | sed 's/.* \([0-9]\+\).*/\1/;q')
echo "gcc  major version : $gcc_major"
echo "gnat major version : $gnat_major"

check() {
    status=0
    (gprbuild -vh p.gpr || status=$?) | tee log
    test $status = 0
    (grep '^/usr/bin/gcc' || status=$?) | tee gcc_lines
    test $status = 0
    grep -v "^/usr/bin/gcc$1" gcc_lines || status=$?
    test $status = 1
}

echo "A pure Ada project must only call gcc-$gnat_major."
cat > m.adb <<EOF
with Ada.Text_IO;
procedure M is
begin
   Ada.Text_IO.Put_Line ("Hello from Ada.");
end M;
EOF
cat > p.gpr <<EOF
project P is
   for Main use ("m.adb");
end P;
EOF
check "-$gnat_major "
./m

find . -type f -delete

echo 'A pure C project must only call gcc without version suffix.'
cat > m.c <<EOF
#include <stdio.h>
int main(void) {
   printf("Hello from C.\n");
   return 0;
}
EOF
cat > p.gpr <<EOF
project P is
   for Languages use ("C");
   for Main use ("m.c");
end P;
EOF
check ' '
./m

find . -type f -delete

echo "Mixed projects must only call gcc-$gnat_major."
cat > m.adb <<EOF
with Ada.Text_IO;
procedure M is
   procedure C_Call with Import, Convention => C;
begin
   Ada.Text_IO.Put_Line ("Hello from Ada.");
   C_Call;
end M;
EOF
cat > c.c <<EOF
#include <stdio.h>
void c_call(void)
{
   printf("Hello from C.\n");
}
EOF
cat > p.gpr <<EOF
project P is
   for Languages use ("Ada", "C");
   for Main use ("m.adb");
end P;
EOF
gprconfig --batch --config=Ada --config=C,,,,gcc-$gnat_major
check "-$gnat_major"
./m
