#!/bin/sh
# Installs the .deb packages in DIR with apt, in a throwaway container (CI),
# with /usr/local's libraries moved away first and the distribution
# upgraded to what it is today, and checks that every program and library
# in them finds all it loads. Where they carry libraries of their own
# (/usr/lib/MULTIARCH/cont8nuum), also that Mesa still finds every symbol
# it needs with ours loaded in their place (as in c8, where ours come
# first and Mesa gets them too), and that none of ours is older than the
# distribution's. Not for a real system.
#
#   packaging/deb/test-debs.sh DIR
set -eu
dir=$(cd "$1" && pwd)
[ -f /run/.containerenv ] || [ -f /.dockerenv ] || {
	echo "test-debs: only in a container" >&2; exit 1; }

mkdir -p /tmp/usr-local-lib
find /usr/local/lib* -name 'lib*.so*' -exec mv {} /tmp/usr-local-lib/ \;
ldconfig

export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get upgrade -y -qq >/dev/null
apt-get install -y -qq --no-install-recommends "$dir"/*.deb >/dev/null

bad=0
for p in $(cd "$dir" && ls *.deb | sed 's/_.*//'); do
	for f in $(dpkg -L "$p"); do
		[ -f "$f" ] && [ ! -L "$f" ] || continue
		head -c4 "$f" | grep -q '^.ELF' || continue
		missing=$(ldd "$f" 2>&1 | grep 'not found' || true)
		if [ -n "$missing" ]; then
			echo "test-debs: $f: $missing" >&2
			bad=1
		fi
	done
done

priv=/usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/cont8nuum
if [ -d "$priv" ]; then
	sys=${priv%/cont8nuum}
	# Each of ours against the distribution's copy of the same soname
	for l in "$priv"/lib*.so.*; do
		[ -L "$l" ] || continue
		so=${l##*/}
		[ -e "$sys/$so" ] || continue
		ours=$(basename "$(readlink -f "$l")")
		theirs=$(basename "$(readlink -f "$sys/$so")")
		newest=$(printf '%s\n%s\n' "$ours" "$theirs" | sort -V | tail -1)
		if [ "$newest" != "$ours" ] && [ "$ours" != "$theirs" ]; then
			echo "test-debs: the distribution's $theirs is newer than ours, $ours: raise its pin in private-libs.sh" >&2
			bad=1
		else
			echo "== $so: ours $ours, the distribution's $theirs"
		fi
	done
	# Mesa with ours in place: no symbol it needs may go missing
	apt-get install -y -qq --no-install-recommends libgl1-mesa-dri \
		libegl-mesa0 libgbm1 mesa-vulkan-drivers >/dev/null
	mesa=$(dpkg -L libgl1-mesa-dri libegl-mesa0 libgbm1 mesa-vulkan-drivers |
		grep '\.so' | sort -u)
	n=0
	for f in $mesa; do
		[ -f "$f" ] && [ ! -L "$f" ] || continue
		ldd -r "$f" 2>&1 | grep -E 'undefined symbol|not found' | sort > /tmp/before || true
		LD_LIBRARY_PATH=$priv ldd -r "$f" 2>&1 |
			grep -E 'undefined symbol|not found' | sort > /tmp/after || true
		new=$(comm -13 /tmp/before /tmp/after)
		if [ -n "$new" ]; then
			echo "test-debs: Mesa's $f with ours: $new" >&2
			bad=1
		fi
		n=$((n + 1))
	done
	echo "== Mesa ($(dpkg-query -W -f '${Version}' libgl1-mesa-dri)): $n libraries, nothing missing with ours"
fi
[ "$bad" = 0 ] || exit 1
echo "== installed and all found: $(cd "$dir" && ls *.deb | sed 's/_.*//' | tr '\n' ' ')"
