#!/usr/bin/make -f
## -*- makefile -*-

export DEB_BUILD_MAINT_OPTIONS=hardening=+all
export QT_SELECT=qt6
export LC_ALL=C.UTF-8

## Out-of-source build directory per arch
BUILD_DIR = obj-$(DEB_HOST_MULTIARCH)

%:
	dh $@ --buildsystem=qmake --builddirectory=$(BUILD_DIR)

## Minimal overrides: configure, install, clean
override_dh_auto_configure:
	mkdir -p $(BUILD_DIR)
	cd $(BUILD_DIR) && qmake6 $(CURDIR)/bianbu-locale.pro

override_dh_auto_install:
	dh_auto_install --buildsystem=qmake --builddirectory=$(BUILD_DIR) -- INSTALL_ROOT=$(CURDIR)/debian/bianbu-locale
	## Generate .qm files if not built already
	set -e; LRELEASE_BIN="$$(command -v lrelease-qt6 2>/dev/null || command -v /usr/lib/qt6/bin/lrelease 2>/dev/null || command -v lrelease 2>/dev/null)"; \
	if [ -z "$$LRELEASE_BIN" ]; then echo "[i18n] No lrelease tool found"; exit 1; fi; \
	for ts in $(CURDIR)/src/plugin/translations/bianbu-locale_*.ts; do \
	  [ -f "$$ts" ] || continue; \
	  qm="$${ts%.ts}.qm"; \
	  if [ -f "$$qm" ]; then \
	    echo "[i18n] Skipping $$ts (QM already exists)"; \
	    continue; \
	  fi; \
	  echo "[i18n] Generating QM from $$ts using $$LRELEASE_BIN"; \
	  QT_SELECT= "$$LRELEASE_BIN" "$$ts" >/dev/null || { echo "lrelease failed for $$ts"; exit 1; }; \
	done
	## Install translations
	set -e; \
	for f in $(CURDIR)/src/plugin/translations/bianbu-locale_*.qm; do \
	  [ -f "$$f" ] || continue; \
	  base=$${f##*/}; \
	  lang=$${base#bianbu-locale_}; lang=$${lang%.qm}; \
	  dest="$(CURDIR)/debian/bianbu-locale/usr/share/locale/$$lang/LC_MESSAGES"; \
	  mkdir -p "$$dest"; \
	  cp -f "$$f" "$$dest/bianbu-locale.qm"; \
	done
	## Install desktop file
	mkdir -p $(CURDIR)/debian/bianbu-locale/usr/share/applications
	cp -f $(CURDIR)/data/bianbu-locale.desktop $(CURDIR)/debian/bianbu-locale/usr/share/applications/

# Skip dh_install since we install directly
override_dh_install:
	@echo "Files installed directly, skipping dh_install"

override_dh_auto_clean:
	dh_auto_clean --buildsystem=qmake --builddirectory=$(BUILD_DIR) || true
	rm -rf $(BUILD_DIR)
	find $(CURDIR)/src -name "*.qm" -delete || true
