VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
COMMIT  ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo none)
PKG     := git.zb-server.de/ZB-Server/uptimesebi
LDFLAGS := -s -w -X $(PKG)/internal/buildinfo.Version=$(VERSION) -X $(PKG)/internal/buildinfo.Commit=$(COMMIT)

.PHONY: generate web build test lint release dev-up dev-up-sentinel dev-down migrate image

generate:
	sqlc generate
	go tool templ generate

web:
	npm run build

build: generate web
	CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o bin/ ./cmd/...

test:
	# Integration tests share one Postgres and Redis database, so packages run one at a time.
	go test -p 1 ./...

lint:
	golangci-lint run

# Tags the next release from the Conventional Commits since the last one;
# pushing the tag publishes it. CHANNEL=beta tags a prerelease.
CHANNEL ?= stable
release:
	@test "$$(git rev-parse --abbrev-ref HEAD)" = main || { echo "release from main" >&2; exit 1; }
	@git diff --quiet HEAD || { echo "commit or stash your changes first" >&2; exit 1; }
	@git fetch -q --tags origin main
	@test "$$(git rev-parse HEAD)" = "$$(git rev-parse origin/main)" || { echo "main is not origin/main" >&2; exit 1; }
	@tag="$$(go run ./tools/release next $(CHANNEL))" && \
		git tag -a "$$tag" -m "$$tag" && \
		go run ./tools/release notes "$$tag" && \
		echo "Tagged $$tag. Publish it with: git push origin $$tag"

dev-up:
	docker compose up -d --wait

dev-up-sentinel:
	docker compose --profile sentinel up -d --wait

dev-down:
	docker compose --profile sentinel down

migrate:
	go run ./cmd/api migrate up

image:
	docker build --build-arg VERSION=$(VERSION) --build-arg COMMIT=$(COMMIT) -t uptimesebi:$(VERSION) .
