fail()
{
	echo
	echo "Test setup failed: $@"
	echo
	exit 1
}

makedir()
{
	rm -rf "$1"
	mkdir -p "$1" || fail "could not mkdir $1"
}

cdir()
{
	cd "$1" || fail "could not cd to $1"
}

build_and_install()
{
	# Create a build directory, and fill it with the source.
	makedir "$build"
	makedir "$build/test"

	ls ../ | while read f ; do
		[ "$f" = "test" ] && continue
		[ "$f" = ".git" ] && continue
		cp -a ../"$f" "$build" || fail "could not copy ../$f to $build"
	done || exit 1

	tolink="$build/utest/test_cmd.c"
	# Add some hard links, to make the test harder.
	ln "$tolink" "$build/utest/testhardlink1" || fail
	ln "$tolink" "$build/utest/testhardlink2" || fail
	ln "$tolink" "$build/utest/testhardlink3" || fail
	ln "$tolink" "$build/utest/testhardlink4" || fail
	# Add a file starting with a character whose ASCII number is greater
	# than 127, to check for differences between client phase1 sorting and
	# server sorting.
	touch "$build/utest/á" || fail
	# Add some wide-character directories/files.
	cp -ar china-data "$build"

	# Create a .bz2 file, to exercise exclude_comp.
	# Some tars (like on NetBSd) do not like having '..' in the arguments.
	# So cd up and back again.
	cdir ..
	tar -cjf "$build/autoconf/autoconf.tar.bz2" autoconf || fail
	cdir -

	# Create a target directory, compile burp and install it into the
	# target.
	makedir "$target"
	cdir "$build"
	make clean
	./configure --prefix=/usr --sysconfdir=/etc/burp --localstatedir=/var || fail "configure failed"
	make || fail "make failed"
	# For some reason, make is not returning an error code.
	# Look for important binaries before carrying on.
	[ -x burp ] || fail "make failed to build burp"
	make install-all DESTDIR="$target" || fail "make install failed"
	[ -x "$target/usr/bin/vss_strip" ] \
		|| fail "make failed to install vss_strip"
	[ -h "$target/usr/sbin/bedup" ] \
		|| fail "make failed to install bedup"
	[ -h "$target/usr/sbin/bsigs" ] \
		|| fail "make failed to install bsigs"
	cdir -
}

build_and_install
