#!/usr/bin/make -f

%:
	dh $@

LANG_APPROX = ast be gl nn oc se tg uk
# bo, dz?
# kab?
# km?
# lo?
# tl? https://github.com/espeak-ng/espeak-ng/issues/581

# Will be in next espeak-ng release: he th ug uk

include /usr/share/dpkg/architecture.mk

ifeq (,$(filter noudeb, $(DEB_BUILD_PROFILES)))
  with_udeb = yes
endif

UDEB_CFLAGS ?= $(CFLAGS) -Os
UDEB_LDLIBS ?= /usr/lib/$(DEB_HOST_MULTIARCH)/libespeak-ng.a /usr/lib/$(DEB_HOST_MULTIARCH)/libsonic.a /usr/lib/$(DEB_HOST_MULTIARCH)/libpcaudio.a -lm -lpthread -lasound -lrt

UDEB_LDFLAGS ?= $(LDFLAGS) -u _Unwind_Resume -u __gcc_personality_v0 -u _Unwind_ForcedUnwind -u _Unwind_GetCFA -u _Unwind_GetBSP -lgcc_s -Wl,--defsym,create_pulseaudio_object=create_alsa_object $(UDEB_LDLIBS)

UDEB_BUILT_USING := $(shell dpkg-query -f '$${source:Package} (= $${source:Version}), ' -W libespeak-ng-libespeak-dev libsonic-dev libpcaudio-dev)

ESPEAK_NG_VERSION=$(shell dpkg-query -W -f '$${source:Version}' libespeak-ng-dev | cut -d - -f 1)

override_dh_clean:
	dh_clean
	debconf-updatepo

override_dh_auto_clean:
	dh_auto_clean -B build-deb
ifeq ($(with_udeb),yes)
	dh_auto_clean -B build-udeb
endif

override_dh_auto_configure:
	dh_auto_configure -B build-deb
ifeq ($(with_udeb),yes)
	CFLAGS="$(UDEB_CFLAGS)" LDFLAGS="$(UDEB_LDFLAGS)" dh_auto_configure -B build-udeb
endif

override_dh_auto_build:
	# Check whether we still want the quirks in espeakup-udeb.restart
	for lang in $(LANG_APPROX) ; do \
	  if grep -r "^language $$lang" /usr/lib/*/espeak-ng-data/lang ; then exit 1 ; fi \
	done

	dh_auto_build -B build-deb
ifeq ($(with_udeb),yes)
	dh_auto_build -B build-udeb
endif

override_dh_auto_install:
	dh_auto_install -B build-deb --destdir=debian/espeakup
ifeq ($(with_udeb),yes)
	dh_auto_install -B build-udeb --destdir=debian/espeakup-udeb
endif

override_dh_install:
	dh_install
ifeq ($(with_udeb),yes)
	install -m0644 debian/espeakup-udeb.start debian/espeakup-udeb/lib/debian-installer-startup.d/S51espeakup
	install -m0755 debian/espeakup-udeb.finish-install debian/espeakup-udeb/usr/lib/finish-install.d/06espeakup
	install -m0755 debian/espeakup-udeb.restart debian/espeakup-udeb/usr/lib/espeakup/espeakup.restart
endif

override_dh_installinit:
	dh_installinit -- start 10 S .

override_dh_gencontrol:
ifeq ($(with_udeb),yes)
	echo 'espeak-ng:Version=$(ESPEAK_NG_VERSION)' >> debian/espeakup-udeb.substvars
	echo 'built-using=$(UDEB_BUILT_USING)' >> debian/espeakup-udeb.substvars
endif
	dh_gencontrol

override_dh_installsystemd:
	dh_installsystemd --restart-after-upgrade
