# VibeDNS
#
# The binary is self-contained: templates, assets and migrations are embedded,
# and the SQLite driver is pure Go, so no CGO or C toolchain is involved.

BINARY      := vibedns
PKG         := ./cmd/vibedns
VERSION     ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
COMMIT      ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo unknown)
BUILD_DATE  ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
VERSION_PKG := github.com/owen/vibedns/internal/version

LDFLAGS := -s -w \
	-X $(VERSION_PKG).Version=$(VERSION) \
	-X $(VERSION_PKG).Commit=$(COMMIT) \
	-X $(VERSION_PKG).BuildDate=$(BUILD_DATE)

export CGO_ENABLED := 0

.PHONY: all
all: build

.PHONY: build
build: ## Build the binary
	go build -trimpath -ldflags="$(LDFLAGS)" -o $(BINARY) $(PKG)

.PHONY: install
install: ## Install into GOPATH/bin
	go install -trimpath -ldflags="$(LDFLAGS)" $(PKG)

.PHONY: test
test: ## Run the test suite
	go test ./...

.PHONY: test-race
test-race: ## Run the tests with the race detector
	CGO_ENABLED=1 go test -race ./...

.PHONY: cover
cover: ## Write and open a coverage report
	go test -coverprofile=coverage.out ./...
	go tool cover -html=coverage.out

.PHONY: vet
vet: ## Run go vet
	go vet ./...

.PHONY: fmt
fmt: ## Format the source
	gofmt -s -w .

.PHONY: check
check: fmt vet test ## Format, vet and test

.PHONY: run
run: build ## Run against a local database on non-privileged ports
	./$(BINARY) serve --db ./data/dns.db --dns 127.0.0.1:5353 --http 127.0.0.1:8080

.PHONY: clean
clean: ## Remove build output
	rm -f $(BINARY) coverage.out
	rm -rf dist out

.PHONY: dist
dist: ## Cross-compile release binaries
	@mkdir -p dist
	@for target in linux/amd64 linux/arm64 linux/arm darwin/amd64 darwin/arm64 freebsd/amd64; do \
		os=$${target%/*}; arch=$${target#*/}; \
		echo "building $$os/$$arch"; \
		GOOS=$$os GOARCH=$$arch go build -trimpath -ldflags="$(LDFLAGS)" \
			-o dist/$(BINARY)-$$os-$$arch $(PKG) || exit 1; \
	done
	@echo "binaries written to dist/"

.PHONY: docker
docker: ## Build the container image
	docker build \
		--build-arg VERSION=$(VERSION) \
		--build-arg COMMIT=$(COMMIT) \
		--build-arg BUILD_DATE=$(BUILD_DATE) \
		-t vibedns:$(VERSION) -t vibedns:latest .

.PHONY: help
help: ## List targets
	@grep -hE '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) \
		| awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-14s\033[0m %s\n", $$1, $$2}'
