#!/usr/bin/env bash
#
# Run builds and tests on Amazon virtual machines.

prog=$(basename $0)
DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)

usage()
{
	echo "usage: $prog tarfile directory" 1>&2
	exit 1
}

tarfile="$1"
directory="$2"
[ -n "$tarfile" ] || usage
[ -n "$directory" ] || usage
[ -f "$tarfile" ] || fail "tarfile $tarfile does not exist"

. "$DIR"/vms_shared || fail
. "$DIR"/vms_ids || fail
instanceids="$ubuntuid
$windowsid"
[ -n "$instanceids" ] || fail
restart_instanceids "$instanceids"
get_summary "$instanceids"

host="ubuntu@$ubuntu"
ssh_opts="-i /var/lib/jenkins/aws/ubfree.pem -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"

# It is possible for the machine to be up, but for sshd to not yet be running.
# Try multiple times for the initial connect.
attempts=0
attempts_max=50
while true ; do
	ssh $ssh_opts "$host" true && break
	attempts=$((attempts+1))
	[ "$attempts" = "$attempts_max" ] && \
		fail "Could not make initial ssh connection after $attempts"
done

ssh $ssh_opts "$host" "rm -rf $tarfile $directory /tmp/burp_ca.lock" \
	|| fail "cleaning ubuntu machine"
ssh $ssh_opts "$host" "rm -rf burp-2.*" \
	|| fail "cleaning ubuntu machine"
scp $ssh_opts "$tarfile" "$host:" \
	|| fail "scp $tarfile to ubuntu machine"
ssh $ssh_opts "$host" "tar -xvf $tarfile" \
	|| fail "unpacking $tarfile"
ssh $ssh_opts "$host" \
	"cd $directory && ./configure --prefix=/usr --sysconfdir=/etc/burp --localstatedir=/var --with-coverage && make coverage" \
		|| fail "make coverage"
scp -r $ssh_opts "$host:$directory/burp-coverage" . \
	|| fail "copying code coverage"
ssh $ssh_opts "$host" \
	"cd $directory && make clean && cd test && make test" \
		|| fail "make test"
ssh $ssh_opts "$host" \
	"cd $directory && ./configure --prefix=/usr --sysconfdir=/etc/burp --localstatedir=/var && cd src/win32 && make && make WIN64=yes" \
		|| fail "building windows installers"
ssh $ssh_opts "$host" \
	"cd $directory/test && ./test_windows64 $ubuntu $windows Administrator" \
		|| fail "running windows tests"
scp -r $ssh_opts "$host:$directory/src/win*/release*/burp-win*installer*.exe" . || fail "copying windows installers"
ssh $ssh_opts "$host" "rm -rf $tarfile $directory" \
	|| fail "cleaning ubuntu machine"

stop_instanceids "$instanceids"

echo "Everything succeeded."

exit 0
