APP      = archivmail
IMPORTER = archivmail-import
EXPORTER = archivmail-export
VERSION ?= 0.1.0
LDFLAGS = -X main.Version=$(VERSION) -s -w

.PHONY: all build clean install

all: build

# Build — CGO-frei, Manticore Search als Volltext-Backend
build:
	CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o bin/$(APP)      ./cmd/archivmail
	CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o bin/$(IMPORTER) ./cmd/archivmail-import
	CGO_ENABLED=0 go build -ldflags "$(LDFLAGS)" -o bin/$(EXPORTER) ./cmd/archivmail-export

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/archivmail-test/{store,logs}
	./bin/archivmail --config config/config.test.yml &
	sleep 2
	bash smoke_test.sh
	pkill archivmail || 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 755 bin/$(EXPORTER) /usr/bin/$(EXPORTER)
	install -D -m 644 config/config.yml /etc/archivmail/config.yml
	install -D -m 644 debian/archivmail.service /lib/systemd/system/archivmail.service
	useradd --system --no-create-home --shell /usr/sbin/nologin archivmail 2>/dev/null || true
	mkdir -p /var/archivmail/{store,astore}
	mkdir -p /var/log/archivmail
	chown -R archivmail:archivmail /var/archivmail /var/log/archivmail
	systemctl daemon-reload
