.PHONY: help matrix lint test clean

SHELL := /bin/bash
IMAGE_PREFIX := remote-users-fact-test

help: ## Show this help
	@grep -E '^[a-zA-Z_-]+:.*##' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*##"}; {printf "  \033[36m%-20s\033[0m %s\n", $$1, $$2}'

matrix: ## Print the test matrix as JSON
	@python3 ci/build_matrix.py

lint: ## Run yamllint and ansible-lint
	yamllint roles/
	ansible-lint

test: ## Run tests on all distros from the matrix
	@python3 ci/build_matrix.py | python3 -c "\
	import sys, json; \
	matrix = json.load(sys.stdin); \
	[print(e['slug'] + ' ' + e['image'] + ' ' + e['platform']) for e in matrix]" | \
	while read slug image platform; do \
		$(MAKE) _test-one SLUG=$$slug IMAGE=$$image PLATFORM=$$platform; \
	done

test-%: ## Run test on a single distro (e.g. make test-el9)
	@python3 ci/build_matrix.py | python3 -c "\
	import sys, json; \
	slug = '$(*)';\
	matrix = json.load(sys.stdin); \
	matches = [e for e in matrix if e['slug'] == slug]; \
	assert matches, f'Unknown slug: {slug}. Valid: {[e[\"slug\"] for e in matrix]}'; \
	e = matches[0]; print(e['slug'] + ' ' + e['image'] + ' ' + e['platform'])" | \
	while read slug image platform; do \
		$(MAKE) _test-one SLUG=$$slug IMAGE=$$image PLATFORM=$$platform; \
	done

_test-one:
	@echo "=== Testing $(SLUG) ($(IMAGE)) ==="
	@dockerfile=ci/Dockerfile.el; \
	if [ "$(PLATFORM)" = "Debian" ] || [ "$(PLATFORM)" = "Ubuntu" ]; then \
		dockerfile=ci/Dockerfile.debian; \
	fi; \
	docker build \
		--build-arg "IMAGE=$(IMAGE)" \
		-t "$(IMAGE_PREFIX)-$(SLUG)" \
		-f "$$dockerfile" . \
	&& docker run --rm "$(IMAGE_PREFIX)-$(SLUG)"
	@echo "=== $(SLUG) OK ==="

clean: ## Remove test Docker images
	@python3 ci/build_matrix.py | python3 -c "\
	import sys, json; \
	[print('$(IMAGE_PREFIX)-' + e['slug']) for e in json.load(sys.stdin)]" | \
	while read img; do \
		docker rmi $$img 2>/dev/null || true; \
	done
	@echo "Clean done."
