#! /bin/sh

set -e
umask 022

DEB_VERSION=$(dpkg-parsechangelog -S Version)
DEB_HOST_MULTIARCH=$(dpkg-architecture -qDEB_HOST_MULTIARCH)

# arguments in form pkg1=custom-version pkg2=version2...
custvers="$*"

make_shlibs() {
	pkg=$1
	PKGDIR=debian/$pkg/DEBIAN

	# shorctcut if no libs and no python libs
	# (or no package at all)
	[ -d $PKGDIR/usr/lib/$DEB_HOST_MULTIARCH -o \
	  -d $PKGDIR/usr/lib/python3 ] || continue

	ver=${DEB_VERSION}
	for v in $custvers; do
	    case "$v" in
		( $pkg=* ) ver=${v#*=}; break;;
	    esac
	done
	echo $pkg $ver

	# step 1:
	# - create symbols files:
	#   - we only want symbols for public libraries (exclude private libs)
	#   - we want to fail if new symbols appear, which are not listed in
	#     the symbols file (dpkg-gensymbols -c4)
	# - create first part of the shlibs file:
	#   for public libraries, we want a weak version dependency
	dh_makeshlibs -p$pkg -V"$pkg (>= ${ver%-*})" -X/usr/lib/${DEB_HOST_MULTIARCH}/samba -X/usr/lib/python3 -- -c4 -v$ver
	[ -e $PKGDIR/shlibs ] && mv $PKGDIR/shlibs $PKGDIR/shlibs.1

	# step 2:
	# - ignore the symbols file generated by this step (it might contain
	#   private symbols):
	#   - output to /dev/null (-O/dev/null)
	#   - don't print info about new symbols (-q)
	# - create second part of the shlibs file:
	#   for private libraries, we want a strict version dependency
	#   this step will generate a strict dependency for all libraries (also
	#   public ones), so afterwards, we will have to merge them
	dh_makeshlibs -p$pkg -V"$pkg (= $ver)" -- -q -O/dev/null -v$ver

	if [ -e $PKGDIR/shlibs -a -e $PKGDIR/shlibs.1 ]; then
		# append entries from 2nd file if they are not in 1st
		exec <$PKGDIR/shlibs.1; seen=
		while read lib rest; do seen="$seen|$lib"; done
		exec <$PKGDIR/shlibs
		while read lib rest; do
			case "$seen|" in (*"|$lib|"*) continue;; esac
			echo "$lib $rest"
		done >>$PKGDIR/shlibs.1
		exec <&-
		mv -f $PKGDIR/shlibs.1 $PKGDIR/shlibs
	elif [ -e $PKGDIR/shlibs.1 ]; then
		mv $PKGDIR/shlibs.1 $PKGDIR/shlibs
	fi
}

# dh_shlibdeps handles -Nfoo passed from dh sequence in d/rules, too
for pkg in $(dh_listpackages)
do
	make_shlibs $pkg
done
