#!/bin/bash
#
# Test a burp client on the same machine as the server, but interact with the
# client over ssh.

myscript=$(basename $0)
if [ ! -f "$myscript" ] ; then
	echo "Please run $myscript whilst standing in the same directory" 1>&2
	exit 1
fi

path="$PWD"
build="$path/build"
target="$path/target"

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 -ar ../"$f" "$build" || fail "could not copy ../$f to $build"
	done || exit 1

	# Create a target directory, compile burp and install it into the
	# target.
	makedir "$target"
	cdir "$build"
	make clean
	./configure || fail "configure failed"
	make || fail "make failed"
	# For some reason, make is not returning an error code.
	# Look for important binaries before carrying on.
	[ -f src/burp ] || fail "make failed"
	[ -f src/bedup ] || fail "make failed"
	make install DESTDIR="$target" || fail "make install failed"
	cdir -
}

build_and_install

# args:
# 1 - directory where build was installed
# 2 - location of client burp
# 3 - location of client conf (for editing)
# 4 - location of client conf (for giving as option to burp binary)
# 5 - directory to backup
# 6 - directory to restore to
# 7 - address of the server
# 8 - ssh command (leave unset for self test)
# 9 - scp command (leave unset for self test)
# 10 - address of the client (leave unset for self test)
./test_main \
	"$target" \
	"$target/usr/sbin/burp" \
	"$target/etc/burp/burp.conf" \
	"$target/etc/burp/burp.conf" \
	"$build" \
	"/tmp/restore" \
	127.0.0.1 \
	"ssh" \
	"scp" \
	"localhost" || exit 1

exit 0
