ABRA         := ./cmd/abra
XGETTEXT     := go run git.coopcloud.tech/toolshed/xgettext-go@latest
COMMIT       := $(shell git rev-list -1 HEAD)
GOPATH       := $(shell go env GOPATH)
GOVERSION    := 1.26
LDFLAGS      := "-X 'main.Commit=$(COMMIT)'"
DIST_LDFLAGS := $(LDFLAGS)" -s -w"
BFLAGS       := -v -trimpath
GCFLAGS      := "all=-l -B"
DOMAIN       := abra
POFILES      := $(wildcard pkg/i18n/locales/*.po)
MOFILES      := $(patsubst %.po,%.mo,$(POFILES))
LINGUAS      := $(basename $(POFILES))

export GOPRIVATE=coopcloud.tech

all: format check build

run:
	@go run -gcflags=$(GCFLAGS) -ldflags=$(LDFLAGS) $(ABRA)

install:
	@go install -gcflags=$(GCFLAGS) -ldflags=$(LDFLAGS) $(ABRA)

build:
	@go build $(BFLAGS) -gcflags=$(GCFLAGS) -ldflags=$(DIST_LDFLAGS) $(ABRA)

build-docker:
	@docker run -it -v $(PWD):/abra golang:$(GOVERSION) \
		bash -c 'cd /abra; ./scripts/docker/build.sh'

clean:
	@rm '$(GOPATH)/bin/abra'

format:
	@gofmt -s -w $$(find . -type f -name '*.go' | grep -v "/vendor/")

check:
	@test -z $$(gofmt -l $$(find . -type f -name '*.go' | grep -v "/vendor/")) || \
	(echo "gofmt: formatting issue - run 'make format' to resolve" && exit 1)

test:
	@go test ./... -cover -v -p 1

find-tests:
	@find . -name "*_test.go"

loc:
	@find . -name "*.go" | xargs wc -l

deps:
	@go get -t -u ./...

.PHONY: i18n
i18n: update-pot update-pot-po-metadata update-po build-mo

.PHONY: update-po
update-po:
	@set -eu; \
	for lang in $(LINGUAS); do \
		msgmerge --backup=none -U $$lang.po pkg/i18n/locales/$(DOMAIN).pot; \
	done

.PHONY: update-pot
update-pot:
	@$(XGETTEXT) \
		-o pkg/i18n/locales/$(DOMAIN).pot \
		--keyword=i18n.G \
		--keyword-ctx=i18n.GC \
		--sort-output \
		--add-comments-tag="translators" \
		$$(find . -name "*.go" -not -path "*vendor*" | sort)

.PHONY: update-pot-po-metadata
update-pot-po-metadata:
	@sed -i "s/charset=CHARSET/charset=UTF-8/g" pkg/i18n/locales/*.po pkg/i18n/locales/*.pot

.PHONY: build-mo
build-mo:
	@set -eu; \
	for lang in $(POFILES); do \
		msgfmt $$lang -o $$(echo $$lang | sed 's/.po/.mo/g') --statistics; \
	done

release:
	@goreleaser release --clean
