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

include /usr/share/dpkg/default.mk

export DEB_BUILD_MAINT_OPTIONS=hardening=+all

# These are used for cross-compiling and for saving the configure script
# from having to guess our platform (since we know it already)
include /usr/share/dpkg/architecture.mk

CFLAGS += -flto
LDFLAGS += -flto

%:
	dh $@ --buildsystem=pybuild

override_dh_auto_configure:
	# build nox version first
	CFLAGS="$(CFLAGS)" ./configure -C --host=$(DEB_HOST_GNU_TYPE) --build=$(DEB_BUILD_GNU_TYPE) --prefix=/usr --without-x
	$(MAKE) CFLAGS="$(CFLAGS)" CPPFLAGS="$(CPPFLAGS)" LDFLAGS="$(LDFLAGS)"
	cp src/cluster cluster.nox
	$(MAKE) clean
	# now configure X version
	CFLAGS="$(CFLAGS)" ./configure -C --host=$(DEB_HOST_GNU_TYPE) --build=$(DEB_BUILD_GNU_TYPE) --prefix=/usr --with-x

override_dh_auto_build-arch:
	# $(MAKE) CFLAGS="$(CFLAGS)" CPPFLAGS="$(CPPFLAGS)" LDFLAGS="$(LDFLAGS)"
	$(MAKE) -C X11
	$(MAKE) -C src
	cp src/cluster cluster.x

override_dh_auto_build-indep:
	#error with prefix defined:  perl Makefile.PL prefix=$(CURDIR)/debian/$(DEB_SOURCE)/usr/
	perl Makefile.PL INSTALL_BASE=$(CURDIR)/debian/cluster3/usr/
	make
	make test
	make install

cluster3.1: debian/cluster3.sgml
	docbook-to-man $< > $@

xcluster3.1: debian/xcluster3.sgml
	docbook-to-man $< > $@

override_dh_auto_clean:
	dh_auto_clean
	rm -f cluster.nox cluster.x src/*.o X11/*.o X11/*.a src/cluster X11/cluster src/Makefile src/Makefile.old X11/Makefile Makefile MANIFEST
	rm -rf X11/.deps/ config.cache config.h config.log config.status src/.deps/ stamp-h1

override_dh_install:
	dh_install
	mkdir -p $(CURDIR)/debian/$(DEB_SOURCE)/usr/bin
	mv cluster.x $(CURDIR)/debian/$(DEB_SOURCE)/usr/bin/xcluster3
	mv cluster.nox $(CURDIR)/debian/$(DEB_SOURCE)/usr/bin/cluster3
	mkdir -p $(CURDIR)/debian/$(DEB_SOURCE)/usr/share/doc/$(DEB_SOURCE)
	cp doc/* $(CURDIR)/debian/$(DEB_SOURCE)/usr/share/doc/$(DEB_SOURCE)
	# upstream Makefile installs copy of html documentation to unusual place - remove it
	find debian/$(DEB_SOURCE)/usr -type d -name cluster | xargs rm -rf
	# upstream Makefile installs executable cluster in /usr/bin - conflicting name, we are using cluster3
	find debian/$(DEB_SOURCE)/usr/bin -type f -name cluster -delete
	# Remove __pycache__ that remains from build time test
	find . -name __pycache__ -type d | xargs rm -rf
