# Auto-detect docker or podman (prefer docker, fall back to podman)
CONTAINER_CMD := $(firstword $(shell for cmd in docker podman; do command -v $$cmd 2>/dev/null && echo $$cmd && break; done))
ifeq ($(strip $(CONTAINER_CMD)),)
$(error neither docker nor podman is installed on your system)
endif

VERSION     = $(shell grep '^version' Cargo.toml | sed 's/.*= "\(.*\)"/\1/')
IMAGE       ?= pumlv
REGISTRY    ?= docker.io/okieoth
PLANTUML    ?= /opt/plantuml.jar
DIAGRAMS    ?= .

.PHONY: build test run docker-build docker-push \
        check-uncommitted check-tag tag \
        publish-dry-run publish version

# ── Development ───────────────────────────────────────────────────────────────

build:
	cargo test
	cargo build --release

test:
	cargo test

run:
	cargo run -- --plantuml $(PLANTUML) $(DIAGRAMS)

# ── Docker ────────────────────────────────────────────────────────────────────

docker-build:
	$(CONTAINER_CMD) build -t $(REGISTRY)/$(IMAGE):$(VERSION) -t $(REGISTRY)/$(IMAGE):latest .

docker-push:
	$(CONTAINER_CMD) push $(REGISTRY)/$(IMAGE):$(VERSION)
	$(CONTAINER_CMD) push $(REGISTRY)/$(IMAGE):latest

# ── Release ───────────────────────────────────────────────────────────────────

version:
	@echo $(VERSION)

check-uncommitted:
	@if [ -n "$$(git status -s)" ]; then \
		echo "there are uncommitted changes ... cancel"; \
		exit 1; \
	else \
		echo "nothing to commit :) ..."; \
	fi

check-tag:
	@if git tag -l | grep -qx "$(VERSION)"; then \
		echo "the required version \"$(VERSION)\" is already tagged ... cancel"; \
		exit 1; \
	else \
		echo "tag available :) ..."; \
	fi

tag:
	git tag $(VERSION)

publish-cargo-dry-run:
	cargo publish --dry-run

publish-cargo:
	cargo publish


publish-dry-run: check-uncommitted check-tag test docker-build publish-cargo-dry-run
	@echo "dry-run ok — would push $(REGISTRY)/$(IMAGE):$(VERSION)"

publish: check-uncommitted check-tag test tag docker-build publish-cargo docker-push
