#!/usr/bin/make -f

LDFLAGS=$(shell dpkg-buildflags --get LDFLAGS)
CFLAGS=$(shell dpkg-buildflags --get CFLAGS)
LDFLAGS+=-Wl,--as-needed -Wl,-O1

# waf, thank you _so_ much
export LINKFLAGS=$(LDFLAGS)
export CCFLAGS=$(CFLAGS)

export DEB_BUILD_HARDENING=1

CMD=$(shell echo $@ | sed 's/override_//')

LIBWEBKIT_PKG=$(shell dpkg-query -p libwebkitgtk-dev | grep Depends | sed -r 's/.*(libwebkitgtk[^ ]+).*/\1/')
GTKLAUNCHER=$(shell dpkg-query -L $(LIBWEBKIT_PKG) | grep GtkLauncher)
DISTRO=$(shell lsb_release -is)
CONFIG_FILE=debian/config/$(DISTRO).h
ifneq (0, $(shell test -e $(CONFIG_FILE); echo "$$?"))
	DISTRO=Debian
endif

%:
	dh $@

WAF=./waf

debian/presubj: debian/presubj.in
	@echo "presubj parameters:"
	@echo "Replacing %LIBWEBKIT_PKG% with $(LIBWEBKIT_PKG)"
	@echo "Replacing %GTKLAUNCHER% with $(GTKLAUNCHER)"
	test -f "/var/lib/dpkg/info/$(LIBWEBKIT_PKG).list"
	test -f "$(GTKLAUNCHER)"
	test -n "$(GTKLAUNCHER)"
	sed -e "s,%LIBWEBKIT_PKG%,$(LIBWEBKIT_PKG),g" -e "s,%GTKLAUNCHER%,$(GTKLAUNCHER),g" $@.in > $@

override_dh_install: debian/presubj
	$(CMD) --fail-missing

override_dh_auto_clean:
	$(WAF) --nocache distclean
	rm -rf _build_
	rm -rf .waf*
	rm -rf .lock-wscript

override_dh_auto_configure:
	$(WAF) --nocache configure --debug-level=none --prefix /usr

override_dh_auto_build:
	$(WAF) build --nocache -v

#override_dh_auto_test:
#	xvfb-run $(WAF) --nocache check

override_dh_auto_install:
	$(WAF) --nocache install --destdir debian/tmp
	rm -f debian/tmp/usr/share/doc/midori/COPYING debian/tmp/usr/share/doc/midori/TRANSLATE
	install -m 0644 debian/$(DISTRO)-config debian/tmp/etc/xdg/midori/config

PRIORITY=$(shell sed -r -e '/DEBIAN_WWW_ALTERNATIVES_PRIORITY/ !d' -e 's/.* ([^ ]*)$$/\1/' $(CONFIG_FILE))

debian/midori.postinst: debian/midori.postinst.base
	sed "s/DEBIAN_WWW_ALTERNATIVES_PRIORITY/$(PRIORITY)/g" debian/midori.postinst.base > debian/midori.postinst

override_dh_installdeb: debian/midori.postinst
	$(CMD)

override_dh_strip:
	$(CMD) --dbg-package=midori-dbg

override_dh_installchangelogs:
	rm -f debian/midori/usr/share/doc/midori/ChangeLog
	dh_installchangelogs ChangeLog
