#!/bin/bash
#
# This creates a self-contained copy of the twopence test server
# for things like mounting into a container
#

if [ $# -eq 1 ]; then
	binary=$(twopence show-path test_server)
	imagedir=$1
elif [ $# -eq 2 ]; then
	binary=$1
	imagedir=$2
fi

if [ -z "$binary" -o ! -x "$binary" ]; then
	echo "Cannot find test server binary at $binary" >&2
	exit 1
fi

set -e

mkdir -p $imagedir

function _ldd {

	ldd "$@" | grep '=>' | awk '{print $3}'
}

function copy_libs {

	count=$(_ldd $binary | wc -l)
	echo "Copying $count libraries to $imagedir"

	_ldd $binary |
		while read lib; do
			if [ -s $lib ]; then
				rm -f $imagedir/$(basename $lib)
				cp $lib $imagedir
			fi
		done
}

function copy_binary {

	echo "Copying $binary to $imagedir"
	cp $binary $imagedir/_test_server
}

function create_wrapper {

	echo "Creating shell wrapper"
	cat >$imagedir/twopence-test-server <<-"EOF"
	#!/bin/bash
	#
	# In order to use this in a container, try something like this:
	#
	# podman run --mount type=bind,src=/usr/lib/twopence/sidecar,target=/mnt -it <image> \
	#		/mnt/twopence-test-server --port-tcp 5000
	#

	dir=$(dirname $0)
	export LD_LIBRARY_PATH=$dir
	exec $dir/_test_server "$@"
EOF

	chmod 755 $imagedir/twopence-test-server
}

copy_libs
copy_binary
create_wrapper
