#!/bin/bash
set -e
set -o pipefail

version=$1; shift

# We wrap all of the programs in /usr/bin with a script
# (xen-utils-wrapper) which chooses the version corresponding to the
# currently-running version of Xen.  The actual binaries go
# in xen-utils-$version:usr/lib/xen-$version/bin
#
# We use ldd to see what libraries the binary is linked against.
# We ignore errors from ldd because we are running it on scripts
# and things too and it is hard to distinguish these errors.
#
# We then match against the libraries listed for inclusion here:
list=debian/libxenmiscV.install.vsn-in

t=debian/tmp
vd=/usr/lib/xen-$version/bin
cd=/usr/lib/xen-common/bin

mkdir -p $t/$vd

for binary in `find $t/usr/{bin,sbin} -type f`; do
	reason=''
	{ ldd "$binary" ||: ; } | { fgrep '=>' ||: ; } \
	| (
		while read lib dummy; do
			lib=${lib%.so.*}
			if grep -F "usr/lib/*/$lib.so.*" $list >/dev/null; then
				reason+=" $lib"
			fi
		done

		if [ "x$reason" = x ]; then
			exit 0
		fi

		echo "shuffling $binary $reason"

		leaf=${binary##*}
		mv -v $binary $t/$vd/$leaf
		ln -vs $cd/xen-utils-wrapper $binary

		touch debian/shuffle-binaries.stamp
	)
done

ls debian/shuffle-binaries.stamp
