#!/usr/bin/make -f
DEB_HOST_ARCH_OS ?= $(shell dpkg-architecture -qDEB_HOST_ARCH_OS)

# Enable hardening features for daemons
# Note: blhc (build log hardening check) will find these false positivies: CPPFLAGS 2 missing, LDFLAGS 1 missing
export DEB_BUILD_MAINT_OPTIONS=hardening=+bindnow,+pie
DPKG_EXPORT_BUILDFLAGS = 1
# Include buildflags.mk so we can append to the vars it sets.
include /usr/share/dpkg/buildflags.mk

# Vendor and version (after buildflags.mk so we don't overwrite CXXFLAGS)
version := $(shell dpkg-parsechangelog -SVersion).$(shell dpkg-vendor --query Vendor)
CXXFLAGS += -DPACKAGEVERSION='"$(version)"'

# for atomic support on mips(el)
LDFLAGS += -latomic

# Disable systemd integration on non-linux archs
ifeq ($(DEB_HOST_ARCH_OS),linux)
CONFIGURE_ARGS += --enable-systemd --with-systemd=/lib/systemd/system
else
CONFIGURE_ARGS += --disable-systemd
endif

SUBSTVARS = -Vbuild:PublicSuffixVersion=$(shell (dpkg-query -W publicsuffix | awk '{print $$2}'))


# Use new build system
%:
	dh $@

override_dh_auto_clean:
	dh_auto_clean
	rm -f effective_tld_names.dat
	chmod +x mkpubsuffixcc || true

override_dh_auto_configure:
	cp -f /usr/share/publicsuffix/public_suffix_list.dat effective_tld_names.dat
	dh_auto_configure -- \
		--sysconfdir=/etc/powerdns \
		--enable-reproducible \
		--with-lua \
		--with-protobuf=yes \
		$(CONFIGURE_ARGS)

override_dh_auto_install:
	dh_auto_install
	rm -f debian/pdns-recursor/etc/powerdns/recursor.conf-dist
	./pdns_recursor --no-config --config | sed \
		-e 's!# config-dir=.*!config-dir=/etc/powerdns!' \
		-e 's!# local-address=.*!local-address=127.0.0.1!' \
		-e 's!# quiet=.*!quiet=yes!' \
		-e 's!# setgid=.*!setgid=pdns!' \
		-e 's!# setuid=.*!setuid=pdns!' \
		-e 's!# hint-file=.*!&\nhint-file=/usr/share/dns/root.hints!' \
		-e 's!# security-poll-suffix=.*!&\nsecurity-poll-suffix=!' \
		> debian/pdns-recursor/etc/powerdns/recursor.conf
ifeq ($(DEB_HOST_ARCH_BITS),32)
	echo RestrictAddressFamilies is broken on 32bit, removing it from service file
	perl -ni -e 'print unless /RestrictAddressFamilies/' debian/pdns-recursor/lib/systemd/system/*.service
endif

override_dh_strip:
	dh_strip --ddeb-migration='pdns-recursor-dbg'

override_dh_installinit:
	dh_installinit --error-handler=initscript_error

override_dh_gencontrol:
	dh_gencontrol -- $(SUBSTVARS)

