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

export DH_VERBOSE=1
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)

override_dh_auto_configure:
	mkdir -p $(BUILD_DIR)
	cd $(BUILD_DIR) && qmake6 $(CURDIR)/bianbu-control-center-shell.pro

override_dh_auto_build:
	dh_auto_build --buildsystem=qmake --builddirectory=$(BUILD_DIR)

override_dh_auto_install:
	install -d $(CURDIR)/debian/bianbu-control-center-shell/usr/bin
	if [ -f "$(BUILD_DIR)/build/bianbu-control-center-shell" ]; then \
	  install -m 0755 "$(BUILD_DIR)/build/bianbu-control-center-shell" "$(CURDIR)/debian/bianbu-control-center-shell/usr/bin/bianbu-control-center-shell"; \
	elif [ -f "$(BUILD_DIR)/bianbu-control-center-shell" ]; then \
	  install -m 0755 "$(BUILD_DIR)/bianbu-control-center-shell" "$(CURDIR)/debian/bianbu-control-center-shell/usr/bin/bianbu-control-center-shell"; \
	else \
	  echo "Binary not found in $(BUILD_DIR)/build/ or $(BUILD_DIR)/" >&2; \
	  exit 1; \
	fi
	install -d $(CURDIR)/debian/bianbu-control-center-shell/usr/share/applications
	install -m 0644 $(CURDIR)/runtime/bianbu-control-center-shell.desktop $(CURDIR)/debian/bianbu-control-center-shell/usr/share/applications/
	# Generate missing .qm files if not built already (following bianbu-accounts pattern)
	set -e; LRELEASE_BIN="$(shell 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)/app/translations/bianbu-control-center-shell_*.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 (rename to match domain)
	set -e; \
	for f in $(CURDIR)/app/translations/bianbu-control-center-shell_*.qm; do \
	  [ -f "$$f" ] || continue; \
	  basename=$$(basename $$f .qm); \
	  locale=$${basename#*_}; \
	  dest="$(CURDIR)/debian/bianbu-control-center-shell/usr/share/locale/$$locale/LC_MESSAGES"; \
	  mkdir -p "$$dest"; \
	  cp -f "$$f" "$$dest/bianbu-control-center-shell.qm"; \
	  echo "[i18n] Installed translation: $$f -> $$locale"; \
	done

override_dh_auto_clean:
	dh_auto_clean --buildsystem=qmake --builddirectory=$(BUILD_DIR) || true
	rm -rf $(BUILD_DIR)
	rm -f Makefile .qmake.stash
