.PHONY: test-setup test distclean

LTS_CODENAME = $(shell dpkg-parsechangelog --show-field distribution -l ../debian/changelog | sed 's/^xivo-//' )
HOST_USER=$(shell whoami)
COMPOSE_FILES = $(wildcard assets/*/docker-compose.yml)

test-setup: build-amid
	docker pull p0bailey/docker-flask
	docker pull dokku/wait

build-amid:
	docker build --no-cache -t xivo/xivo-amid ..
	docker build --no-cache -t xivo-amid-tests -f Dockerfile ..

test:
	docker run --rm \
		-v /var/run/docker.sock:/var/run/docker.sock \
		-v /etc/localtime:/etc/localtime:ro \
		-v /etc/timezone:/etc/timezone:ro \
		-v /etc/group:/etc/group:ro \
		-v /etc/passwd:/etc/passwd:ro \
		-v /etc/shadow:/etc/shadow:ro \
		-v "`pwd`/..":"`pwd`/.." \
		-w "`pwd`" \
		--network host \
		xivoxc/debian-builder-$(LTS_CODENAME):latest \
		/bin/bash -c "python3 -m venv /tmp/venv3; \
			source /tmp/venv3/bin/activate; \
			pip install --upgrade pip; \
			pip install -r test-requirements.txt; \
			cd .. ; python setup.py install ; cd - ;\
			python3 -m unittest -v"

test-debug:
	docker run --rm -it \
		-v /var/run/docker.sock:/var/run/docker.sock \
		-v /etc/localtime:/etc/localtime:ro \
		-v /etc/timezone:/etc/timezone:ro \
		-v /etc/group:/etc/group:ro \
		-v /etc/passwd:/etc/passwd:ro \
		-v /etc/shadow:/etc/shadow:ro \
		-v "`pwd`/..":"`pwd`/.." \
		-w "`pwd`" \
		--network host \
		xivoxc/debian-builder-$(LTS_CODENAME):latest

# This is to be run after the tests were run to fix perms
# of files created during instantiation of the integration test
# (for example if the project was installed with python setup.py ...)
fix-perms:
	docker run --rm \
		-v /etc/localtime:/etc/localtime:ro \
		-v /etc/timezone:/etc/timezone:ro \
		-v /etc/group:/etc/group:ro \
		-v /etc/passwd:/etc/passwd:ro \
		-v /etc/shadow:/etc/shadow:ro \
		-v "`pwd`/..":"`pwd`/.." \
		-w "`pwd`" \
		--network host \
		xivoxc/debian-builder-$(LTS_CODENAME):latest \
		/bin/bash -c "chown -R $(HOST_USER):$(HOST_USER) ../"

stop:
	@$(foreach cpf,$(COMPOSE_FILES),$(shell docker compose -f $(cpf) kill))

clean:
	@$(foreach cpf,$(COMPOSE_FILES),$(shell docker compose -f $(cpf) down))

distclean: fix-perms stop clean
	docker rmi -f xivo/xivo-amid
	docker rmi -f xivo-amid-tests
	docker network prune -f
