SHELL := /bin/sh

GO ?= go
TEA ?= tea
GOARCH ?= amd64
REMOTE ?= origin

VERSION := $(shell sed -n 's/^const version = "\([^"]*\)".*/\1/p' cmd/fancywin/main.go)
HOST_GOOS := $(shell $(GO) env GOHOSTOS)
HOST_GOARCH := $(shell $(GO) env GOHOSTARCH)
TAG := v$(VERSION)
BINARY := dist/fancywin.exe
CONFIG := dist/fancywin.yaml
CHECKSUM := $(BINARY).sha256

.PHONY: build release

build:
	@test -n "$(VERSION)" || { echo "Could not read the FancyWin version" >&2; exit 1; }
	mkdir -p dist
	GOOS=$(HOST_GOOS) GOARCH=$(HOST_GOARCH) $(GO) test -buildvcs=false ./...
	CGO_ENABLED=0 GOOS=windows GOARCH=$(GOARCH) $(GO) build \
		-buildvcs=false \
		-trimpath \
		-ldflags='-s -w' \
		-o $(BINARY) \
		./cmd/fancywin
	cp fancywin.example.yaml $(CONFIG)
	@echo "Built $(BINARY) for windows/$(GOARCH) (FancyWin $(VERSION))"

release: build
	@command -v $(TEA) >/dev/null 2>&1 || { echo "The Gitea tea CLI is required for releases" >&2; exit 1; }
	@test -z "$$(git status --porcelain)" || { echo "Refusing to release from a dirty working tree" >&2; exit 1; }
	@test "$$(git rev-parse HEAD)" = "$$(git rev-parse '@{upstream}')" || { echo "Refusing to release: HEAD has not been pushed to its upstream branch" >&2; exit 1; }
	@! git rev-parse --verify --quiet "refs/tags/$(TAG)" >/dev/null || { echo "Tag $(TAG) already exists locally" >&2; exit 1; }
	sha256sum $(BINARY) > $(CHECKSUM)
	$(TEA) releases create \
		--remote $(REMOTE) \
		--tag $(TAG) \
		--target "$$(git rev-parse HEAD)" \
		--title "FancyWin $(VERSION)" \
		--note "Portable FancyWin $(VERSION) build for Windows $(GOARCH)." \
		--asset $(BINARY) \
		--asset $(CHECKSUM)
	@echo "Released FancyWin $(VERSION) as $(TAG)"
