SHELL=@SHELL@
INSTALL=@INSTALL@
GETTEXTDIR=@GETTEXT_DIRNAME@
PACKAGE_NAME=@PACKAGE_NAME@

MSGFMT=@MSGFMT@
MSGINIT=@MSGINIT@
MSGMERGE=@MSGMERGE@
XGETTEXT=@XGETTEXT@
ifneq ($(MSGMERGE),)
  MSGMERGE_VERSION=$(shell echo $(word 2,$(sort $(shell $(MSGMERGE) --version | head -n 1))) | cut -f 1-2 -d ".")
else
  MSGMERGE_VERSION=0.0
endif
ifneq ($(MSGMERGE_VERSION),0.10)
  MSGMERGE_OPTS=--backup=simple --suffix=.backup --update
else
  MSGMERGE_OPTS=-o $@
endif
XGETTEXT_OPTS=-LC -j -d$(PACKAGE_NAME) -k_

SOURCE_FILES=$(shell find ../src -name "*.[ch]" 2>/dev/null)
POT_FILE=$(PACKAGE_NAME).pot
PO_FILES=$(shell ls -1 *.po 2>/dev/null)
MO_FILES=$(patsubst %.po, %.mo, $(PO_FILES))

.PHONY:all
all: $(MO_FILES)

%.mo: %.po
	@if ( test "$(MSGFMT)" ); then \
	  echo -n "$@: "; \
	  $(MSGFMT) -v -o $@ $<; \
	fi

%.po: $(POT_FILE)
	@if ( ! test -e $@ ); then \
	  if ( test "$(MSGINIT)" ); then \
	    $(MSGINIT) -i $< -o $@; \
	  fi \
	else \
	  if ( test -e $< ) ; then \
	    if ( test "$(MSGMERGE)" ); then \
	      echo -n "$@: Merging from $<"; \
	      $(MSGMERGE) $(MSGMERGE_OPTS) $@ $<; \
	      touch $@; \
	    fi \
	  fi \
	fi

.PHONY: update
update:
	@$(MAKE) template $(PO_FILES)

.PHONY:template
template:
	@if ( test "$(XGETTEXT)" ); then \
	  if (test -e $(POT_FILE)); then rm -f $(POT_FILE); fi; \
	  echo -n "Creating gettext template file $(POT_FILE)"; \
	  touch $(POT_FILE); \
	  for i in $(SOURCE_FILES); do \
	    $(XGETTEXT) $(XGETTEXT_OPTS) -o $(POT_FILE) $$i; \
	    echo -n "."; \
	  done; \
	  echo "done"; \
	fi

$(POT_FILE): $(SOURCE_FILES)
	@$(MAKE) template

.PHONY:install-%.mo
install-%.mo: %.mo
	$(INSTALL) -d $(DESTDIR)$(GETTEXTDIR)/$*/LC_MESSAGES; \
	$(INSTALL) -m 644 $< $(DESTDIR)$(GETTEXTDIR)/$*/LC_MESSAGES/$(PACKAGE_NAME).mo; \

.PHONY:install
install: $(patsubst %,install-%,$(MO_FILES))

.PHONY:uninstall
uninstall:
	-rm -f  $(DESTDIR)$(GETTEXTDIR)/*/LC_MESSAGES/$(PACKAGE_NAME).mo;

.PHONY:clean
clean:
	-rm -f *.mo

.PHONY: distclean
distclean: clean
	-rm -f $(POT_FILE)
