# -*- mode: makefile; coding: utf-8 -*-

POLINT := $(BINDIR)polint
PYBABEL := $(BINDIR)pybabel
POBUGSADDR := lele@metapensiero.it
POCOPYRIGHT := "Lele Gaifax"
PBEXTRACT = $(PYBABEL) extract --project=SoL \
			       --version=$(VERSION) \
			       --add-comments=TRANSLATORS: \
			       --msgid-bugs-address=$(POBUGSADDR) \
			       --copyright-holder=$(POCOPYRIGHT) \
			       --sort-output
LOCALEDIR := src/sol/locale
PBUPDATE := $(PYBABEL) update --output-dir $(LOCALEDIR) --previous
PBCOMPILE := $(PYBABEL) compile --directory $(LOCALEDIR) --statistics
PBINIT := $(PYBABEL) init --output-dir $(LOCALEDIR)
PBCLIENT_DOMAIN := sol-client
PBCLIENT_MAP := $(LOCALEDIR)/$(PBCLIENT_DOMAIN).cfg
PBCLIENT_POT := $(LOCALEDIR)/$(PBCLIENT_DOMAIN).pot
PBCLIENT_POs := $(wildcard $(LOCALEDIR)/*/LC_MESSAGES/*-client.po)
PBCLIENT_MOs := $(patsubst %.po,%.mo,$(PBCLIENT_POs))
PBSERVER_DOMAIN := sol-server
PBSERVER_MAP := $(LOCALEDIR)/$(PBSERVER_DOMAIN).cfg
PBSERVER_POT := $(LOCALEDIR)/$(PBSERVER_DOMAIN).pot
PBSERVER_POs := $(wildcard $(LOCALEDIR)/*/LC_MESSAGES/*-server.po)
PBSERVER_MOs := $(patsubst %.po,%.mo,$(PBSERVER_POs))

define fix-first-author =
for po in $(PBCLIENT_POs) $(PBSERVER_POs); do \
  sed -i -e "s/^# FIRST AUTHOR <EMAIL@ADDRESS>,.*$$/# `git log --date=format:%Y --pretty=format:'%cN <%cE>, %ad.' $$po | tail -1`/" $$po; \
done
endef

.PHONY: update-catalogs
update-catalogs:
	$(PBEXTRACT) --mapping $(PBCLIENT_MAP) --output $(PBCLIENT_POT) src/sol
	$(PBEXTRACT) --mapping $(PBSERVER_MAP) --output $(PBSERVER_POT) src/sol
	$(PBUPDATE) --domain $(PBCLIENT_DOMAIN) --input-file $(PBCLIENT_POT)
	$(PBUPDATE) --domain $(PBSERVER_DOMAIN) --input-file $(PBSERVER_POT)
	$(fix-first-author)

%-client.mo: %-client.po
	$(PBCOMPILE) --domain $(PBCLIENT_DOMAIN)

%-server.mo: %-server.po
	$(PBCOMPILE) --domain $(PBSERVER_DOMAIN)

.PHONY: compile-catalogs
compile-catalogs: $(PBCLIENT_MOs) $(PBSERVER_MOs)

.PHONY: init-catalog-%
init-catalog-%:
	$(PBINIT) --locale $(@:init-catalog-%=%) --domain $(PBCLIENT_DOMAIN) \
		  --input-file $(LOCALEDIR)/$(PBCLIENT_DOMAIN).pot
	$(PBINIT) --locale $(@:init-catalog-%=%) --domain $(PBSERVER_DOMAIN) \
		  --input-file $(LOCALEDIR)/$(PBSERVER_DOMAIN).pot

.PHONY: lint
lint::
	@$(POLINT) $(LOCALEDIR)/*/LC_MESSAGES/*.po
