# Housecarl build.
#
#   make              build bin/housecarld and bin/hc (and their bash completion)
#   make test         vet, gofmt check and unit tests
#   make logo         rebuild the web UI's logo and the README banner from artwork/
#   make dist         static binaries for linux/amd64 and linux/arm64 in dist/
#   make cli-dist     the CLI alone for Linux, macOS and Windows in dist/
#                     (housecarl-cli-<version>-<os>-<arch>[.exe])
#
# Installing, the systemd unit and the Debian packages come with the daemon
# (as in Steward's Makefile).

VERSION ?= $(shell cat VERSION 2>/dev/null || echo 0.0.0-dev)
# RELEASE_TAG marks a build of a release (the web UI then shows and links
# the release rather than the commit): set when HEAD is tagged v$(VERSION)
# and no tracked file is changed.
RELEASE_TAG ?= $(shell t=v$(VERSION); git tag --points-at HEAD 2>/dev/null | grep -qx "$$t" && git diff --quiet HEAD 2>/dev/null && echo $$t)
# DESCRIBE places other builds relative to the last tag ("3 commits after
# v0.2.0-rc.1").
DESCRIBE ?= $(shell git describe --tags --long --match 'v[0-9]*' --abbrev=12 HEAD 2>/dev/null)
LDFLAGS := -s -w -X housecarl/internal/version.Version=$(VERSION) -X housecarl/internal/version.Tag=$(RELEASE_TAG) \
	-X housecarl/internal/version.Describe=$(DESCRIBE)
GOFLAGS := -trimpath
export CGO_ENABLED := 0

.PHONY: all build completion test vet logo dist cli-dist clean

all: build

build:
	go build $(GOFLAGS) -ldflags '$(LDFLAGS)' -o bin/housecarld ./cmd/housecarld
	go build $(GOFLAGS) -ldflags '$(LDFLAGS)' -o bin/hc ./cmd/hc
	$(MAKE) --no-print-directory completion

# Bash completion scripts, generated by the binaries themselves.
completion:
	@mkdir -p bin/completion
	bin/hc completion bash > bin/completion/hc
	bin/housecarld completion bash > bin/completion/housecarld

vet:
	go vet ./...
	@test -z "$$(gofmt -l cmd internal)" || { echo "gofmt needed:"; gofmt -l cmd internal; exit 1; }

test: vet
	go test ./...

logo:
	python3 scripts/logo.py

dist: build
	for arch in amd64 arm64; do \
		GOOS=linux GOARCH=$$arch go build $(GOFLAGS) -ldflags '$(LDFLAGS)' -o dist/housecarl-$(VERSION)-linux-$$arch/housecarld ./cmd/housecarld && \
		GOOS=linux GOARCH=$$arch go build $(GOFLAGS) -ldflags '$(LDFLAGS)' -o dist/housecarl-$(VERSION)-linux-$$arch/hc ./cmd/hc && \
		tar -C dist -czf dist/housecarl-$(VERSION)-linux-$$arch.tar.gz housecarl-$(VERSION)-linux-$$arch || exit 1; \
	done

# The platforms cli-dist builds the CLI for.
CLI_PLATFORMS ?= linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64 windows/arm64

cli-dist:
	@mkdir -p dist
	for p in $(CLI_PLATFORMS); do \
		os=$${p%/*} arch=$${p#*/} ext=; [ $$os = windows ] && ext=.exe; \
		GOOS=$$os GOARCH=$$arch go build $(GOFLAGS) -ldflags '$(LDFLAGS)' -o dist/housecarl-cli-$(VERSION)-$$os-$$arch$$ext ./cmd/hc || exit 1; \
	done

clean:
	rm -rf bin dist
