APP     = mailarchived
IMPORTER= mailarchive-import
VERSION ?= 0.1.0
LDFLAGS = -X main.Version=$(VERSION) -s -w

.PHONY: all build build-xapian clean install

all: build

# Default build — Bleve index (pure Go, no system deps)
build:
	go build -ldflags "$(LDFLAGS)" -o bin/$(APP)      ./cmd/mailarchived
	go build -ldflags "$(LDFLAGS)" -o bin/$(IMPORTER) ./cmd/importer

# Xapian build — faster at scale, requires: apt install libxapian-dev
build-xapian:
	go build -tags xapian -ldflags "$(LDFLAGS)" -o bin/$(APP)-xapian ./cmd/mailarchived
	go build -tags xapian -ldflags "$(LDFLAGS)" -o bin/$(IMPORTER)    ./cmd/importer

clean:
	rm -rf bin/

test:
	go test -v -race -count=1 ./internal/storage/... ./internal/userstore/... \
	  ./internal/auth/... ./internal/audit/... ./internal/index/... \
	  ./pkg/mailparser/...

test-all:
	go test -v -race -count=1 ./...

test-short:
	go test -short ./...

test-cover:
	go test -coverprofile=coverage.out ./...
	go tool cover -html=coverage.out -o coverage.html
	@echo "Coverage report: coverage.html"

smoke: build
	@echo "Starting daemon in background for smoke test..."
	mkdir -p /tmp/mailarchive-test/{store,index,logs}
	./bin/mailarchived --config config/config.test.yml &
	sleep 2
	bash test/smoke_test.sh
	pkill mailarchived || true

vet:
	go vet ./...

install: build
	install -D -m 755 bin/$(APP)      /usr/bin/$(APP)
	install -D -m 755 bin/$(IMPORTER) /usr/bin/$(IMPORTER)
	install -D -m 644 config/config.yml /etc/mailarchive/config.yml
	install -D -m 644 debian/mailarchive.service /lib/systemd/system/mailarchive.service
	useradd --system --no-create-home --shell /usr/sbin/nologin mailarchive 2>/dev/null || true
	mkdir -p /var/lib/mailarchive/{store,index,attachments,meta}
	mkdir -p /var/log/mailarchive
	chown -R mailarchive:mailarchive /var/lib/mailarchive /var/log/mailarchive
	systemctl daemon-reload
