#!/usr/bin/make -f

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

export DEB_BUILD_MAINT_OPTIONS=hardening=+all

include ./version.mk
MAJOR=$(NETPBM_MAJOR_RELEASE)
MINOR=$(NETPBM_MINOR_RELEASE)
POINT=$(NETPBM_POINT_RELEASE)

#https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1007234#3
#export DEB_CFLAGS_MAINT_APPEND = -fsanitize=undefined -fno-sanitize-recover
#export DEB_LDFLAGS_MAINT_APPEND = -fsanitize=undefined

%:
	dh $@ --no-parallel

override_dh_auto_configure:
	cp config.mk.in config.mk
	cat debian/config.mk.debian >> config.mk
	echo "CFLAGS = `dpkg-buildflags --get CFLAGS`" >> config.mk
ifeq ($(DEB_HOST_ARCH),amd64)
	echo 'WANT_SSE = Y' >> config.mk
endif

override_dh_auto_build:
	dh_auto_build
# build the manpages
	mkdir netpbmdoc
	tar xaf debian/userguide/userguide.tar.xz
	cd netpbmdoc; \
		$(MAKE) USERGUIDE=../userguide/ -f ../buildtools/manpage.mk manpages
	# Fix manual section
	sed -i 's/^\(\.TH "[^"]\+" \)0 /\11 /' netpbmdoc/*.1

override_dh_auto_clean:
	[ ! -f config.mk ] || $(MAKE) distclean
	rm -rf debian/netpbm-test debian/netpbm-test.bak
	rm -rf netpbmdoc userguide

override_dh_auto_install:
	mkdir -p debian/tmp/
	$(MAKE) package PKGDIR=$(CURDIR)/debian/tmp/usr
# install the manpages
	cd netpbmdoc; \
		$(MAKE) USERGUIDE=../userguide/ -f ../buildtools/manpage.mk report
# install pkgconfig
	install -m 0755 -d debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig
	sed -e 's|@INCLUDEDIR@|/usr/include/netpbm|' \
		-e 's|@LINKDIR@|/usr/lib/$(DEB_HOST_MULTIARCH)|' \
		-e 's|@VERSION@|Netpbm $(MAJOR).$(MINOR).$(POINT)|' \
		debian/tmp/usr/pkgconfig_template > debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/netpbm.pc

override_dh_install:
	dh_install
	d-shlibmove --commit \
		    --multiarch \
		    --devunversioned \
		    --exclude-la \
		    --movedev debian/tmp/usr/include usr \
		    --movedev debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig usr/lib/$(DEB_HOST_MULTIARCH) \
		    lib/*.so
	find debian -name "lib*.la" -delete
	rm -rf debian/tmp/usr/sharedlink/libnetpbm
	rm -rf debian/tmp/usr/lib/libnetpbm.so*
	# tool manweb does not work due to missing /etc/manweb.conf
	find . -name "manweb*" -delete

# See bug #1007234
override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	$(MAKE) check-tree RESULTDIR=$(CURDIR)/debian/netpbm-test || true
endif
