#!/usr/bin/make -f

# Uncomment this to turn on verbose mode.
# export DH_VERBOSE=1

include /usr/share/dpkg/pkg-info.mk

export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed

ifneq (,$(filter $(DEB_HOST_ARCH), m68k mipsel sh4))
    export DEB_CXXFLAGS_MAINT_APPEND += -g1
endif

export DEB_BUILD_MAINT_OPTIONS = hardening=+all

MULTIARCH := $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
  EXTRA_MAKE_OPTIONS = -j$(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
endif

CXXFLAGS := $(filter-out -Werror=format-security, $(CXXFLAGS))
CFLAGS := $(filter-out -Werror=format-security, $(CFLAGS))

CHANGELOG_DATE ?= $(shell LC_ALL=C date -u -d @$(SOURCE_DATE_EPOCH) +"%d %B %Y")

%:
	dh $@


override_dh_auto_configure:

override_dh_auto_build:

override_dh_auto_install:
	mkdir -p debian/klayout/usr/lib/klayout
	CC=$(CC) CXX=$(CXX) OBJCOPY=objcopy AR=$(AR) CXXFLAGS="$(CXXFLAGS)" CFLAGS="$(CFLAGS)" ./build.sh -option $(EXTRA_MAKE_OPTIONS) -expert -qmake /usr/lib/$(MULTIARCH)/qt5/bin/qmake -bin $(CURDIR)/debian/klayout/usr/lib/klayout
	mkdir -p debian/klayout/usr/bin
	echo "#!/bin/sh" > debian/klayout/usr/bin/klayout
	echo "LD_LIBRARY_PATH=/usr/lib/klayout exec /usr/lib/klayout/klayout \"\$$@\"" >> debian/klayout/usr/bin/klayout
	mkdir -p debian/klayout/usr/share/pixmaps
	cp etc/logo.png debian/klayout/usr/share/pixmaps/klayout.png

override_dh_fixperms:
	dh_fixperms
	chmod +x debian/klayout/usr/bin/klayout
	# fixing file permissions for *.py files
	for i in `find $(CURDIR)/debian/klayout/usr -type f -name "*.py"`; do \
	    FOUND_PYTHON=$$(head -n1 $$i | grep python); \
	    if [ "$$FOUND_PYTHON" != "" ]; then \
	        chmod +x $$i; \
	    else \
	        chmod -x $$i; \
	    fi; \
	done
	find debian/klayout/usr/lib/klayout -maxdepth 1 -type f -exec chrpath --delete {} \;
	find debian/klayout/usr/lib/klayout -mindepth 1 -type f \( -name "*.so.*" -o -name "*.so" \) -exec chmod -x {} \;
	find debian/klayout/usr/lib/klayout -mindepth 2 -type f -name "*.so*" -exec chrpath --delete {} \;

override_dh_auto_clean:
	dh_auto_clean
	$(RM) -r build-release

override_dh_auto_test:

override_dh_makeshlibs:

override_dh_shlibdeps:
	dh_shlibdeps -l"$(CURDIR)/debian/klayout/usr/lib/klayout:$(CURDIR)/debian/klayout/usr/lib/klayout/lay_plugins:$(CURDIR)/debian/klayout/usr/lib/klayout/db_plugins"

override_dh_installman:
	cd debian/man ; CHANGELOG_DATE="$(CHANGELOG_DATE)" ./genmanpages.sh
	dh_installman

ifeq (mipsel,$(DEB_BUILD_ARCH))
override_dh_dwz:
	# There is not enough memory for running dwz successfully on mipsel.
endif
