#!/bin/sh
# Regenerate the symbols control files (debian/*.symbols) from freshly
# built shared libraries.
#
# Usage:
#   dpkg-buildpackage -b -nc      # build, keeping the staging trees
#   debian/update-symbols.sh      # update debian/*.symbols in place
#   git diff debian/*.symbols     # review, then commit
#
# It reads each existing debian/<pkg>.symbols to learn the SONAME and the
# binary package, locates the matching library under that package's staging
# directory (debian/<pkg>/), and runs dpkg-gensymbols to merge any new
# symbols at the current upstream version. Existing symbols keep the version
# at which they were first recorded.
set -eu

# Run from the source root regardless of where we were invoked from.
cd "$(dirname "$0")/.."

# Upstream version (strip the Debian revision).
version=$(dpkg-parsechangelog -SVersion | sed 's/-[^-]*$//')

status=0
found_any=0
for symfile in debian/*.symbols; do
	[ -e "$symfile" ] || continue
	found_any=1

	# First line: "<soname> <package> #MINVER#"
	read -r soname pkg _ < "$symfile"

	so=$(find "debian/$pkg" -type f -name "$soname.*" 2>/dev/null | head -n1)
	if [ -z "$so" ]; then
		echo "error: $soname not found under debian/$pkg/ -- build the package first (e.g. dpkg-buildpackage -b -nc)" >&2
		status=1
		continue
	fi

	echo "Updating $symfile from $so (version $version)"
	dpkg-gensymbols -p"$pkg" -v"$version" -e"$so" -O"$symfile"
done

if [ "$found_any" = 0 ]; then
	echo "error: no debian/*.symbols files found to regenerate" >&2
	exit 1
fi

exit "$status"
