GO        ?= go
TAGS      ?= vmembed
VERSION   ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
BUILD     ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo unknown)-$(shell date -u +%Y%m%d)
LDFLAGS   := -s -w -X github.com/v10networks/nmon/internal/buildinfo.Version=$(VERSION) -X github.com/v10networks/nmon/internal/buildinfo.Build=$(BUILD)
BIN       := nmon
PG_DSN    ?= postgres://nmon:nmon@localhost:55432/nmon?sslmode=disable

.PHONY: devtools all lint lint-go lint-web build importer build-arm64 build-noembed fetch-vm web test test-integration test-pg test-v6only vet gate-m1 gate-m2 gate-m3 gate-m4 gate-m5 gate-m6 clean

all: build

fetch-vm:
	./scripts/fetch-vm.sh

# The UI is built first, then copied into internal/webui/dist for go:embed (git-ignored).
web:
	@if [ -f web/package.json ]; then \
		cd web && { [ -d node_modules ] || npm ci --no-audit --no-fund; } && npm run build && \
		cd .. && rm -rf internal/webui/dist/* && cp -r web/dist/. internal/webui/dist/ && touch internal/webui/dist/.gitkeep; \
	fi

build: fetch-vm web
	CGO_ENABLED=0 $(GO) build -tags '$(TAGS)' -ldflags '$(LDFLAGS)' -o $(BIN) ./cmd/nmon

# Developer tools (backfill, seed-demo) are a separate binary that is never shipped.
devtools:
	CGO_ENABLED=0 $(GO) build -o nmon-devtools ./cmd/nmon-devtools

build-arm64: fetch-vm web
	CGO_ENABLED=0 GOOS=linux GOARCH=arm64 $(GO) build -tags '$(TAGS)' -ldflags '$(LDFLAGS)' -o $(BIN)-arm64 ./cmd/nmon

importer:
	CGO_ENABLED=0 $(GO) build -ldflags '$(LDFLAGS)' -o nmon-librenms-import ./cmd/nmon-librenms-import

build-noembed:
	CGO_ENABLED=0 $(GO) build -ldflags '$(LDFLAGS)' -o $(BIN) ./cmd/nmon

GOLANGCI := go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.14.0

# Hard rule (docs/MAINTAINABILITY.md): every gate runs this first and it must be clean.
lint: lint-go lint-web

lint-go:
	$(GOLANGCI) run ./...
	./scripts/lint-filesize.sh

lint-web:
	@if [ -f web/package.json ]; then cd web && npm run lint; fi

vet:
	$(GO) vet ./...

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

# Integration tests use fixtures and a real VictoriaMetrics binary extracted by fetch-vm.
test-integration: fetch-vm
	$(GO) test -race -tags 'integration $(TAGS)' ./...

test-pg:
	./scripts/test-pg.sh

test-v6only:
	NMON_TEST_V6ONLY=1 $(GO) test -race -tags 'integration $(TAGS)' ./...

gate-m1 gate-m2 gate-m3 gate-m4 gate-m5 gate-m6: gate-m%:
	./scripts/gate-m$*.sh

clean:
	rm -f $(BIN) $(BIN)-arm64 nmon-devtools nmon-librenms-import
