VERSION := $(shell git describe --tags --always --dirty)

.PHONY: build install test lint fmt dist dist-assets release-vars

build:
	go build -ldflags "-X main.version=$(VERSION)" -o terdut-tui .

install:
	go install -ldflags "-X main.version=$(VERSION)" .

# ci.yaml and release.yaml run `make fmt lint test`, so a green gate here and a green
# pipeline are the same code rather than two descriptions of it. It is also what the
# release skill runs before tagging.

# Covers the API client against a stub server, the sign-in flow, the Update state
# machine, and View rendering -- all pure enough to test without a terminal.
test: ## Run the test suite
	go test ./...

lint: ## go vet
	go vet ./...

# This exists because `go vet` does not look at import order: the move to
# git.ryuvia.com rewrote every import path without re-sorting, the new path sorts
# before github.com/..., and both repos sat unformatted through a green CI run and
# a release before anyone noticed.
#
# Both of gofmt's failure modes need handling, and they are not alike. A file that
# is merely misformatted is listed on stdout with exit 0 -- so the failure has to
# be raised by hand. A file that does not parse is the opposite: nothing on stdout
# and exit 2, which a naive `[ -n "$$unformatted" ]` reads as success. The first
# draft of this target had exactly that hole.
fmt: ## Fail on files that are not gofmt'd
	@if ! unformatted=$$(gofmt -l .); then \
		echo "gofmt could not parse the tree:"; gofmt -l .; exit 1; \
	fi; \
	if [ -n "$$unformatted" ]; then \
		echo "not gofmt'd:"; echo "$$unformatted"; gofmt -d .; exit 1; \
	fi

# What a release publishes. The asset names matter beyond being tidy: internal/updater
# looks for exactly terdut-tui-<tag>-<goos>-<goarch> in the latest release and reports
# every available name when it cannot find one. Renaming the pattern here breaks
# self-update for every installed binary.
DIST_TARGETS := linux/amd64 linux/arm64 darwin/amd64 darwin/arm64

dist: ## Build every release binary into dist/ (VERSION=vX.Y.Z to name them)
	@set -eu; mkdir -p dist; \
	for target in $(DIST_TARGETS); do \
		goos="$${target%/*}"; goarch="$${target#*/}"; \
		out="dist/terdut-tui-$(VERSION)-$$goos-$$goarch"; \
		echo "building $$out"; \
		GOOS="$$goos" GOARCH="$$goarch" go build -ldflags "-X main.version=$(VERSION)" -o "$$out" .; \
	done

# The names dist produces, one per line, so the release skill can check the published
# release has every one of them rather than a count.
dist-assets: ## Print the asset names a release of VERSION carries
	@for target in $(DIST_TARGETS); do \
		echo "terdut-tui-$(VERSION)-$${target%/*}-$${target#*/}"; \
	done

# Read by the release skill for a repo that publishes binaries and no image or chart
# (KIND=binary in .release.conf). There is nothing to say about images or charts.
release-vars: ## Print the variables the release process reads
	@printf 'APP=terdut-tui\n'
