# Entry point for local work and for CI. The Gitea workflows call these same
# targets, so a green `make all` locally means a green pipeline.

REGISTRY  ?= gitea.libretechconsulting.com
NAMESPACE ?= rmcguire

# Every directory under images/ that has a Dockerfile is an image.
IMAGES := $(patsubst images/%/Dockerfile,%,$(wildcard images/*/Dockerfile))

# Build/test a single image with `make build IMAGE=node-agent`; unset means all.
IMAGE   ?=
TARGETS := $(if $(IMAGE),$(IMAGE),$(IMAGES))

# CI overrides REF with the real published ref so the smoke test runs against it.
REF ?=

.DEFAULT_GOAL := help
.PHONY: help list check lint hadolint shellcheck build test all

help: ## Show available targets
	@awk 'BEGIN{FS=":.*##"} /^[a-z][a-z-]*:.*##/ {printf "  \033[36m%-11s\033[0m %s\n",$$1,$$2}' $(MAKEFILE_LIST)

list: ## List every image in this repository
	@printf '%s\n' $(IMAGES)

check: ## Verify each image directory follows the expected layout
	@rc=0; \
	if [ -z "$(IMAGES)" ]; then echo "no images found under images/"; rc=1; fi; \
	for i in $(IMAGES); do \
	  [ -f images/$$i/README.md ] || { echo "images/$$i: missing README.md"; rc=1; }; \
	  if [ -e images/$$i/test.sh ] && [ ! -x images/$$i/test.sh ]; then \
	    echo "images/$$i/test.sh: not executable"; rc=1; \
	  fi; \
	done; \
	[ $$rc -eq 0 ] && echo "layout ok: $(IMAGES)"; \
	exit $$rc

hadolint: ## Lint every Dockerfile
	@hack/lint.sh dockerfiles

shellcheck: ## Lint every shell script
	@hack/lint.sh scripts

lint: hadolint shellcheck ## Run all linters

build: ## Build IMAGE, or every image when IMAGE is unset
	@for i in $(TARGETS); do \
	  echo "==> building $$i"; \
	  docker build -t $(REGISTRY)/$(NAMESPACE)/$$i:dev images/$$i || exit 1; \
	done

test: ## Smoke-test IMAGE, or every image when IMAGE is unset
	@for i in $(TARGETS); do \
	  if [ -x images/$$i/test.sh ]; then \
	    images/$$i/test.sh "$(if $(REF),$(REF),$(REGISTRY)/$(NAMESPACE)/$$i:dev)" || exit 1; \
	  else \
	    echo "==> $$i has no test.sh, skipping"; \
	  fi; \
	done

all: check lint build test ## Everything CI does, locally
