#!/bin/sh
# Smoke test for the AOT and shader toolchain: every binary has to load the
# shared libraries it was linked against, and font-subset has to actually
# subset a font rather than just start.

set -eu

# The tools live in linux-<cpu>, using upstream's cpu names: amd64 is x64 and
# armhf is arm.
case "$(dpkg --print-architecture)" in
	amd64) CPU=x64 ;;
	armhf) CPU=arm ;;
	*) CPU=$(dpkg --print-architecture) ;;
esac
TOOLS=/usr/lib/flutter-engine/linux-$CPU
if [ ! -d "$TOOLS" ]; then
	echo "FAIL: no tool directory for $(dpkg --print-architecture): $TOOLS" >&2
	exit 1
fi

fail=0

# gen_snapshot and impellerc print their usage and exit non-zero when run
# without arguments, which still proves the dynamic loader found every
# dependency; font-subset is covered by the subsetting step below.
for t in gen_snapshot impellerc; do
	err=$("$TOOLS/$t" 2>&1 >/dev/null | head -1)
	case $err in
	*"error while loading shared libraries"*)
		echo "FAIL: $t cannot load its libraries: $err" >&2
		fail=1
		;;
	*)
		echo "ok: $t loads"
		;;
	esac
done

# libpath_ops.so is a Dart FFI target, not a Python extension, so opening it
# with dlopen is what the Flutter tool does with it.
if python3 -c "import ctypes; ctypes.CDLL('$TOOLS/libpath_ops.so')" 2>/dev/null; then
	echo "ok: libpath_ops dlopens"
else
	echo "FAIL: libpath_ops does not dlopen" >&2
	fail=1
fi

# Subset a real font down to "ABC" and check that something smaller came out.
font=/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

echo "65 66 67" | "$TOOLS/font-subset" "$tmp/subset.ttf" "$font" > /dev/null 2>&1 || fail=1
if [ -s "$tmp/subset.ttf" ] &&
   [ "$(stat -c %s "$tmp/subset.ttf")" -lt "$(stat -c %s "$font")" ]; then
	echo "ok: font-subset produced a smaller font"
else
	echo "FAIL: font-subset did not produce a smaller font" >&2
	fail=1
fi

exit $fail
