#!/bin/sh
# Compile and link a trivial program against each embedder through its
# pkg-config file, then run it.  This is what catches a header that moved, a
# .pc that names the wrong -L, or a library the dynamic linker cannot find
# when the program actually starts.

set -eu

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
fail=0

check() {
	pc=$1
	header=$2
	body=$3

	printf '#include <%s>\nint main(void) {\n%s\n}\n' "$header" "$body" \
		> "$tmp/t.c"
	if ! cc "$tmp/t.c" $(pkg-config --cflags --libs "$pc") -o "$tmp/t"; then
		echo "FAIL: cannot build against $pc" >&2
		fail=1
		return
	fi
	if ! "$tmp/t"; then
		echo "FAIL: program linked against $pc does not run" >&2
		fail=1
		return
	fi
	echo "ok: $pc builds and runs"
}

# The C embedder API.  kSuccess is 0, so a non-zero result means the library is
# not the one the header describes.
check flutter_engine flutter_embedder.h \
	'  FlutterEngineProcTable t = {0};
  t.struct_size = sizeof(t);
  return FlutterEngineGetProcAddresses(&t) == kSuccess ? 0 : 1;'

# The GTK embedder.  Constructing and dropping an object proves that the
# library loaded and that its GTK symbols resolve.
check flutter_linux flutter_linux/flutter_linux.h \
	'  GApplication *a = g_application_new("org.debian.FlutterTest", 0);
  g_object_unref(a);
  return 0;'

exit $fail
