BINARY  := emcli
DIST    := dist
VERPKG  := git.dcglab.co.uk/steve/emcli/internal/version

# VERSION defaults to the current git tag/description; override for a release:
#   make release VERSION=v0.4.0
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo v0.0.0-dev)
VER_NO_V := $(patsubst v%,%,$(VERSION))

LDFLAGS := -s -w -X $(VERPKG).String=$(VERSION)

# Platforms to cross-compile for a release. Must match skills/emcli/scripts/install.sh.
PLATFORMS := linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64

.PHONY: build test vet release clean-dist publish

build:
	CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o $(BINARY) ./cmd/emcli

test:
	go test ./...

vet:
	go vet ./...

# release cross-compiles a static binary per platform into dist/, named
# emcli_<version>_<os>_<arch>[.exe], plus a checksums.txt of all assets.
release: clean-dist
	@mkdir -p $(DIST)
	@for p in $(PLATFORMS); do \
		os=$${p%/*}; arch=$${p#*/}; ext=; \
		[ "$$os" = windows ] && ext=.exe; \
		out=$(DIST)/$(BINARY)_$(VER_NO_V)_$${os}_$${arch}$${ext}; \
		echo "  building $$out"; \
		CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch \
			go build -trimpath -ldflags "$(LDFLAGS)" -o $$out ./cmd/emcli || exit 1; \
	done
	@cd $(DIST) && { command -v sha256sum >/dev/null 2>&1 \
		&& sha256sum $(BINARY)_* > checksums.txt \
		|| shasum -a 256 $(BINARY)_* > checksums.txt; }
	@echo "release $(VERSION) artifacts in $(DIST)/:"
	@ls -1 $(DIST)

clean-dist:
	@rm -rf $(DIST)

# publish creates the Gitea release for $(VERSION) and uploads every dist asset.
# Run `make release VERSION=vX.Y.Z` first. Requires the `tea` CLI to be logged in.
publish:
	@test -d $(DIST) || { echo "no $(DIST)/ — run 'make release VERSION=$(VERSION)' first"; exit 1; }
	tea releases create --repo steve/emcli --tag $(VERSION) --title $(VERSION) \
		$(foreach a,$(wildcard $(DIST)/*),--asset $(a))
