#!/usr/bin/make -f

CODENAME ?= $(shell lsb_release -c -s)

export DEB_BUILD_MAINT_OPTIONS ?= hardening=-pie

SHELL = /bin/bash

NUM_CPUS = $(shell getconf _NPROCESSORS_ONLN 2>/dev/null)
PARALLEL = $(subst parallel=,,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
NJOBS    = -j$(or $(PARALLEL),$(NUM_CPUS),1)


DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
DEB_HOST_GNU_TYPE  ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_HOST_ARCH      ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)
DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH 2>/dev/null)


# We don't need to add _FORTIFY_SOURCE here anymore, the upstream build system
# will do that for us on systems which support it and where the compiler does
# not already define it for us.
#
#HARD_CPPFLAGS = -D_FORTIFY_SOURCE=2
HARD_CFLAGS   = -Wformat=2
HARD_LDFLAGS  = -Wl,-z,now

# We don't need to add this here either anymore, the upstream build system will
# also use -fstack-protector-strong where it is supported.
#
#ifneq (,$(filter-out alpha hppa arm, $(DEB_HOST_ARCH)))
#       HARD_CFLAGS += -fstack-protector --param ssp-buffer-size=4
#endif
ifneq (,$(filter-out ia64 hppa avr32, $(DEB_HOST_ARCH)))
        HARD_LDFLAGS += -Wl,-z,relro
endif

# Keep dpkg-buildpackage the hell out of messing with our compile flags,
# we should trust upstream to know better than it what to use here.
# We explicitly re-add -g and -O2 here, since by explicitly overriding
# these variables, we otherwise disable autoconf adding them by default.
CPPFLAGS = $(HARD_CPPFLAGS)
CFLAGS   = $(HARD_CFLAGS) -g -O2
CXXFLAGS = $(HARD_CFLAGS) -g -O2
LDFLAGS  = $(HARD_LDFLAGS)

ifneq (,$(filter $(DEB_HOST_ARCH), arm armel armhf arm64 mips mipsel))
EXTRA_CONFIG_FLAGS += --enable-fixed-point
endif

ifeq (,$(filter $(CODENAME),jessie stretch buster bionic xenial ascii beowulf))
# lucid, precise, etc. GCC older than 4.9
ifneq (,$(filter $(DEB_HOST_ARCH), armhf arm64))
EXTRA_CONFIG_FLAGS += --disable-intrinsics
endif
endif

EXTRA_CONFIG_FLAGS += --disable-doc

%:
	dh $@ --parallel --with autoreconf

override_dh_auto_configure:
	dh_auto_configure -- \
	 --disable-silent-rules \
	 --disable-maintainer-mode \
	 --disable-hardening \
	 $(EXTRA_CONFIG_FLAGS)

override_db_auto_build:
	$(MAKE) $(NJOBS) opus

override_dh_strip:
	dh_strip --dbg-package=libopus-dbg

override_dh_makeshlibs:
	dh_makeshlibs -plibopus0 -- -c0

override_dh_builddeb:
	dh_builddeb -- -Zxz
