# Makefile for coordinating Abacus e2e test stacks and suites.
#
# Example Usage:
#
#   make clean sync_docker # Cleans up workspace and updates docker images
#   make integration_stack # Starts the application stack
#   make test SUITE_NAME=ows_royalties # Runs the passed {SUITE_NAME} tests

.PHONY: clean \
	env_restore env_backup \
	sync_docker docker_down \
	ruby_env local_stack integration_stack \
	lint test test_local \
	e2e_job

clean:
	rm -rf \
		logs \
		env \
		docker_compose/royalties/service_overrides/__pycache__ \
		Gemfile.lock \
		./.env.*.bak

sync_docker: docker_down
	`aws ecr get-login --no-include-email --region us-east-1`
	docker-compose pull -q

docker_down:
	docker-compose down --remove-orphans

integration_stack:
	docker-compose up -d redis \
		postgres \
		cucumber-mysql-royalties
	docker-compose up cucumber-liquibase-runner
	docker-compose up -d \
		abacus-contract \
		abacus-event \
		abacus-state \
		ledger \
		payee \
		payment \
		royalties \
		grass \
		airflow \
		graphql-abacus \
		frontend \
		selenium
	docker-compose up -d https-proxy
	./scripts/wait_for_port.sh http://localhost:6009/hello
	./scripts/wait_for_port.sh http://localhost:6012/hello
	./scripts/wait_for_port.sh http://localhost:6014/hello
	./scripts/wait_for_port.sh http://localhost:6003/hello
	./scripts/wait_for_port.sh http://localhost:6001/hello
	./scripts/wait_for_port.sh http://localhost:6010/hello
	./scripts/wait_for_port.sh http://localhost:6002/hello
	./scripts/wait_for_port.sh http://localhost:6004/hello/
	./scripts/wait_for_port.sh https://localhost:6043/hello/
	./scripts/wait_for_port.sh http://localhost:6000/health
	./scripts/wait_for_port.sh http://localhost:6011/.well-known/apollo/server-health
	docker-compose up -d graphql-gateway
	./scripts/wait_for_port.sh http://localhost:6013/.well-known/apollo/server-health
	docker-compose up -d selenium
	sleep 15  # create a window for things to fully initialize

ruby_env:
	cd .
	ruby -v
	bundle install
	gem install bundler -v "$$(grep -i -A 1 "BUNDLED WITH" Gemfile.lock | tail -n 1 | sed 's/[[:space:]]//g')"

env_backup:
	cp .env ".env.$$(date +%s).bak"
	echo "Backed up .env file in case rake overwrites it."

env_restore:
	cp `ls -1 ./.env.*.bak | sort | tail -n1` .env

lint:
	bundle exec rake ci:pr

test:
	bundle exec rake "ci:${SUITE_NAME}" || (docker-compose logs abacus-contract abacus-event ledger payee payment royalties frontend graphql-abacus graphql-gateway grass https-proxy selenium | grep -v "200 GET /hello" && exit 1)

run_tests:
	cucumber features/standalone -p require_features \
	CUCUMBER_PROFILE=default \
	DOMAIN_PROFILE=developer \
	--tags 'not @wip' \
	--tags 'not @royalties_qa_smoke' \
	--tags "@${SUITE_NAME}" \
	--strict \
	--format pretty \
	--expand

test_local: env_backup run_tests env_restore

local_stack: sync_docker integration_stack ruby_env

e2e_job: clean local_stack test
