# Pekoe Makefile
# Supports: Linux, Windows, FreeBSD, macOS (GNU Make)

BINARY_NAME := pekoe
GO := go

PLATFORMS := linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64 freebsd/amd64

# Version info
# - If git tag exists: version is tag (strip leading "v" if present)
# - If no tag: version is "0.0" + git hash (e.g., 0.0-abcde)
# - If no git repo: version is "unknown"
# Can be overridden via command line: make build VERSION=1.2.3

# Check if .git exists
GIT_EXISTS := $(shell test -d .git && echo yes || echo no)

ifeq ($(GIT_EXISTS),yes)
    # Git repo exists
    GIT_DESCRIBE := $(shell git describe --tags --abbrev=0 2>/dev/null)
    
    ifdef VERSION
        # Manual VERSION override takes priority
        _VERSION := $(VERSION)
    else ifneq ($(GIT_DESCRIBE),)
        # Has tag - use it (strip leading v if present)
        _VERSION := $(shell echo "$(GIT_DESCRIBE)" | sed 's/^v//')
    else
        # No tag - use 0.0 + git hash
        GIT_HASH := $(shell git rev-parse --short=HEAD 2>/dev/null | cut -c1-5)
        _VERSION := 0.0-$(GIT_HASH)
    endif
else
    # No git repo - use unknown
    _VERSION := unknown
endif

VERSION_STRING := $(_VERSION)

# Build flags
LDFLAGS := -s -w -X main.version=$(VERSION_STRING) -X github.com/eleksir/pekoe/internal/server.Version=$(VERSION_STRING)

.PHONY: all
all: clean build

.PHONY: build
build:
	$(GO) build -ldflags "$(LDFLAGS)" -trimpath -o $(BINARY_NAME) ./cmd/pekoe

.PHONY: test
test:
	$(GO) test -v -race ./...

.PHONY: clean
clean:
	-rm -f $(BINARY_NAME) $(BINARY_NAME).exe

.PHONY: build-all
build-all: clean
	@for plt in $(PLATFORMS); do \
		os=$${plt%%/*}; \
		arch=$${plt##*/}; \
		echo "Building $(BINARY_NAME)-$$os-$$arch"; \
		GOOS=$$os GOARCH=$$arch $(GO) build -ldflags "$(LDFLAGS)" -o $(BINARY_NAME)-$$os-$$arch ./cmd/pekoe; \
	done

.PHONY: lint
lint:
	$(GO) vet ./...
ifneq (,$(shell which golangci-lint 2>/dev/null))
	golangci-lint run
endif

.PHONY: install
install: build
	install -m 755 $(BINARY_NAME) /usr/local/bin/

.PHONY: version
version:
	@echo $(VERSION_STRING)

.PHONY: help
help:
	@echo "Pekoe Makefile"
	@echo ""
	@echo "Available targets:"
	@echo "  all        - Clean and build (default)"
	@echo "  build      - Build the binary"
	@echo "  test       - Run tests with race detection"
	@echo "  clean      - Remove built binaries"
	@echo "  build-all  - Cross-compile for all platforms"
	@echo "  lint       - Run linters"
	@echo "  install    - Build and install to PATH"
	@echo "  version    - Show version string"
	@echo "  help       - Show this help message"
	@echo ""
	@echo "Variables:"
	@echo "  VERSION    - Version string (e.g., 1.2.3). Overrides git tag."
	@echo "                Default: git tag or 0 if no tags"
	@echo ""
	@echo "Current version: $(VERSION_STRING)"
	@echo ""
	@echo "Examples:"
	@echo "  make build VERSION=1.0.0     # Build with specific version"
	@echo "  make build-all VERSION=2.0.0  # Cross-compile with version"
	@echo ""
	@echo "Version: $(VERSION_STRING)"
