###############################################################################
# e2e testing helper script
# Preconditions:
# 	- Ran in the top directory of the `beat.web` repository
#	- `Buildout` has already been ran successfully
#	- Default development environment configurations
#	- $SHELL is BASH or ZSH
# Postconditions:
#	- `nohup.out` file will exist in top directory
#	- If there was not a `django.sql3` db file, there will be one
#
# SUGGESTION: The vast majority of the time is spent generating a fresh db via
# `./bin/django install`. You may have a file named `template.django.sql3`
# in the top dir that will be copied and used as the initial db to massively
# speed up testing.
###############################################################################

# clean up any type of exit
trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT

# make sure the beat web server and web manager arent running already
if [ $(ps aux | grep -c 'django runserver') -gt 1 ]
then
	echo 'The BEAT web server is already running locally, aborting...'
	exit -1
fi
if [ $(ps aux | grep -c 'webdriver-manager start') -gt 1 ]
then
	echo 'The webdriver-manager is already running locally, aborting...'
	exit -1
fi

# if db already exists, save it
if [ -a django.sql3 ]
then
	echo 'Found existing django database,' \
		'saving it to "old.django.sql3"...'
	mv django.sql3 old.django.sql3
fi

# Either use a template db...
if [ -a template.django.sql3 ]
then
	echo 'Found template django database, copying it...'
	cp template.django.sql3 django.sql3
else
# ...or generate a new one
	echo 'Found no template db ("template.django.sql3"),' \
		'generating a new db....'
	./bin/django install
fi

# run the web server
beat_cmd='./bin/django runserver'
# spin up web manager
webdriver_cmd='./bin/webdriver-manager start'
# run tests
protractor_cmd='./bin/protractor ./protractor-conf.js'

# start bg processes
echo 'Output from the BEAT web server &' \
	'the Protractor webdriver-manager will be found in nohup.out'
nohup $beat_cmd &
beat_pid=$!
nohup $webdriver_cmd &
webdriver_pid=$!

# couple seconds to let them set up
sleep 2

echo 'Running Protractor....'
echo '----------------'
# run tests
$protractor_cmd

echo '----------------'

# if we saved a db, restore it
if [ -a old.django.sql3 ]
then
	echo 'restoring old database...'
	mv old.django.sql3 django.sql3
fi
