COMMIT ?= $(shell git rev-parse --short HEAD)

# Both deployment hosts are aarch64, so that is the default target. A foreign
# platform needs the *host's* binfmt handlers — podman, unlike docker buildx,
# does not carry its own QEMU — hence the pointer in the failure path.
# Override with e.g. `make build-production PLATFORMS=linux/amd64`.
PLATFORMS ?= linux/arm64
IMAGE ?= registry.tanshu.com/mozimo

# Analytics ids baked into the client bundle — read from the local .env
# (gitignored) and passed to podman build. Empty values disable the tool.
VITE_ENV_KEYS := VITE_GA4_MEASUREMENT_ID VITE_PLAUSIBLE_DOMAIN VITE_SENTRY_DSN
BUILD_ARGS := $(shell for k in VITE_GA4_MEASUREMENT_ID VITE_PLAUSIBLE_DOMAIN VITE_SENTRY_DSN; do \
	v=$$(grep -E "^$$k=" .env 2>/dev/null | head -1 | cut -d= -f2-); \
	[ -n "$$v" ] && printf -- '--build-arg %s=%s ' "$$k" "$$v"; \
	done; true)
BUILD_ARGS += --build-arg VITE_SENTRY_RELEASE=$(COMMIT) --build-arg SENTRY_RELEASE=$(COMMIT)

.PHONY: build-production
build-production: ## Build HEAD with podman for $(PLATFORMS); tag + push :$(COMMIT) and :main
	@echo "▶ podman build --platform $(PLATFORMS) → $(IMAGE):$(COMMIT) + :main"
	@git archive --format=tar HEAD | podman build \
		--platform $(PLATFORMS) \
		--tag $(IMAGE):$(COMMIT) \
		--tag $(IMAGE):main \
		$(BUILD_ARGS) \
		- || { \
		echo "✗ podman build failed."; \
		echo "  Cross-platform builds need binfmt on this host (podman has no built-in QEMU):"; \
		echo "    sudo apt install qemu-user-static    # on an x86_64 host, for $(PLATFORMS)"; \
		exit 1; \
	}
	podman push $(IMAGE):$(COMMIT)
	podman push $(IMAGE):main

.PHONY: build-check
build-check: ## Compile check from HEAD with podman, nothing pushed
	@git archive --format=tar HEAD | podman build \
		--platform $(PLATFORMS) \
		--tag mozimo:check \
		--pull \
		$(BUILD_ARGS) \
		-
