# Tests and checks. The *-docker targets only need Docker.
TEST_IMAGE ?= docker-fence-test:local
SHELLCHECK_IMAGE ?= koalaman/shellcheck:v0.10.0
OLD_BASH_IMAGE ?= bash:4.4
# The entry point is checked with its libraries (-x follows the sources).
SOURCES = docker-fence install.sh tests/stubs/* tests/helpers.bash

.PHONY: test lint check-syntax test-docker lint-docker old-bash-docker ci

test: check-syntax
	bats tests

lint:
	shellcheck -x -P SCRIPTDIR $(SOURCES)

check-syntax:
	@for f in docker-fence install.sh lib/*.sh tests/stubs/*; do bash -n "$$f" || exit 1; done

# Sources are copied into the container (docker cp): this also works
# when the Docker daemon cannot see the working directory.
# $(call docker_run,IMAGE,OPTIONS,COMMAND)
define docker_run
	@id=$$(docker create $(2) -w /src $(1) $(3)) && \
	docker cp "$(CURDIR)/." "$$id:/src" >/dev/null && \
	docker start -a "$$id"; rc=$$?; docker container rm --force "$$id" >/dev/null; exit $$rc
endef

# Tests in a Debian container (bats, iptables). NET_ADMIN allows
# iptables-restore --test, in the network namespace of the container only.
test-docker:
	docker build -q -t $(TEST_IMAGE) tests/docker >/dev/null
	$(call docker_run,$(TEST_IMAGE),--cap-add NET_ADMIN,make test)

lint-docker:
	$(call docker_run,$(SHELLCHECK_IMAGE),,-x -P SCRIPTDIR $(SOURCES))

# bash 4 must be refused with exit code 2.
old-bash-docker:
	$(call docker_run,$(OLD_BASH_IMAGE),,sh -c 'bash /src/docker-fence check; rc=$$?; [ $$rc -eq 2 ] && echo "bash 4: exit 2" || { echo "exit $$rc instead of 2"; exit 1; }')

ci: lint-docker test-docker old-bash-docker
