#!/usr/bin/make -f
SHELL := /bin/bash
export DH_OPTIONS

.PHONY: update
.PHONY: generate-mo

APP_PATH := "usr/lib/iso-constructor"

SOURCE := $(shell dpkg-parsechangelog -S Source)
PYFILES := $(shell find $(APP_PATH) -name '*.py')
UIFILES := $(shell find $(APP_PATH) -name '*.ui')
DTFILES := $(shell find usr/share/applications -name '*.desktop')
POLFILES := $(shell find l10n/input -name '*.policy')
METAINFOFILES := $(shell find l10n/input -name '*.metainfo.xml')

POT := l10n/po/$(SOURCE).pot
PO_DIR := l10n/po

%:
	dh $@ --with=python3

override_dh_auto_clean:
	sudo rm -rf ./$(APP_PATH)/__pycache__/
	rm -rf $(PO_DIR)/mo
	mkdir -p $(PO_DIR)/mo
	po4a --rm-translations l10n/po4a/po4a.conf

override_dh_auto_install: generate-mo update

generate-mo:
	# Get Transifex translations before creating .mo files
	tx pull -a -f
	for PO in $(wildcard $(PO_DIR)/*.po); do \
		LANG=$$(basename "$$PO" .po); \
		mkdir -p $(PO_DIR)/mo; \
		msgfmt "$$PO" -o $(PO_DIR)/mo/$$LANG.mo; \
	done

update:
	# ui files (Gtk4)
	itstool -i l10n/po4a/ui.its -o $(POT).tmp1 $(UIFILES)
	# metainfo files
	itstool -i l10n/po4a/metainfo.its -o $(POT).tmp2 $(METAINFOFILES)
	# policy files
	itstool -i l10n/po4a/polkit.its -o $(POT).tmp3 $(POLFILES)

	# Merge all temporary POT files into the final POT
	msgcat $(POT).tmp1 $(POT).tmp2 $(POT).tmp3 -o $(POT)

	# Clean up temporary files
	rm -f $(POT).tmp1 $(POT).tmp2 $(POT).tmp3

	# py files
	xgettext \
		--join-existing \
		--keyword=_ \
		--language=Python \
		--from-code=UTF-8 \
		--package-name=$(SOURCE) \
		--output=$(POT) \
		$(PYFILES)

	# desktop files
	for LAUNCHER in $(DTFILES); do \
		sed -i '/^.*=\s*$$/d' $$LAUNCHER ; \
		sed -r \
			-e '/^(Name|Comment|GenericName|Keywords)\[/d' \
			-e 's/^(Name=|Comment=|GenericName=|Keywords=)/_\1/' \
			$$LAUNCHER > $$LAUNCHER.in ; \
		intltool-extract --type=gettext/ini $$LAUNCHER.in ; \
		xgettext \
			--join-existing \
			--keyword=N_:1 \
			--output=$(POT) \
			$$LAUNCHER.in.h ; \
		intltool-merge --quiet --desktop-style $(PO_DIR) $$LAUNCHER.in $$LAUNCHER ; \
		rm $$LAUNCHER.in.h $$LAUNCHER.in ; \
	done

	# join translations back into policy files
	for POL in $(POLFILES); do \
		FN=$$(basename $$POL); \
		itstool -j $$POL -o usr/share/polkit-1/actions/$$FN $(PO_DIR)/mo/*.mo; \
	done

	# join translations back into metainfo files
	for META in $(METAINFOFILES); do \
		FN=$$(basename $$META); \
		itstool -j $$META -o usr/share/metainfo/$$FN $(PO_DIR)/mo/*.mo; \
	done

	# Move the .mo files to their final destination
	for MO in $(PO_DIR)/mo/*.mo; do \
		LANG=$$(basename "$$MO" .mo); \
		MO_DIR=$(PO_DIR)/mo/$$LANG/LC_MESSAGES; \
		mkdir -p "$$MO_DIR"; \
		mv "$$MO" "$$MO_DIR/$(SOURCE).mo"; \
	done
