#!/usr/bin/make -f

shellescape='$(subst ','\'',$(1))'
shellexport=$(1)=$(call shellescape,${$(1)})

ifeq (,$(findstring terse,${DEB_BUILD_OPTIONS}))
export DH_VERBOSE=1
export V=1
export VERBOSE=1
endif

LC_ALL:=C
export LC_ALL

DEB_BUILD_ARCH?=$(shell dpkg-architecture -qDEB_BUILD_ARCH)
DEB_HOST_ARCH?=$(shell dpkg-architecture -qDEB_HOST_ARCH)

# is ${CC} defined anywhere (other than implicit rules?)
ifneq (,$(findstring $(origin CC),default undefined))
# no - then default to gcc (or cross-gcc)
ifneq (${DEB_BUILD_ARCH},${DEB_HOST_ARCH})
DEB_HOST_GNU_TYPE?=$(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
CC=			${DEB_HOST_GNU_TYPE}-gcc
else
CC=			gcc
endif
endif

EXTRA_CPPFLAGS=		-DPAX_SAFE_PATH=\"/usr/bin:/bin\"
EXTRA_CFLAGS=		-Wall -Wextra -Wformat -fno-strict-aliasing
EXTRA_CFLAGS+=		-Wno-unused-result
EXTRA_LDFLAGS=		-Wl,--as-needed

ifneq (,$(wildcard /usr/share/dpkg/buildflags.mk))
# dpkg-dev (>= 1.16.1~)
dpkgbuildflagsmkescape=$(subst \,\\\,$(1))
DEB_CFLAGS_MAINT_APPEND=$(call dpkgbuildflagsmkescape,${EXTRA_CFLAGS})
DEB_CPPFLAGS_MAINT_APPEND=$(call dpkgbuildflagsmkescape,${EXTRA_CPPFLAGS})
DEB_LDFLAGS_MAINT_APPEND=$(call dpkgbuildflagsmkescape,${EXTRA_LDFLAGS})
DEB_BUILD_MAINT_OPTIONS=hardening=+all
include /usr/share/dpkg/buildflags.mk
else
# old-fashioned way to determine build flags
CFLAGS=			-O$(if $(findstring noopt,${DEB_BUILD_OPTIONS}),0,2) -g
CFLAGS+=		${EXTRA_CFLAGS}
CPPFLAGS+=		${EXTRA_CPPFLAGS}
LDFLAGS+=		${EXTRA_LDFLAGS}
endif

%:
	dh $@

override_dh_auto_clean:
	rm -rf builddir Makefile

override_dh_auto_build:
	rm -rf builddir
	mkdir builddir
	(cd builddir; env \
	    $(foreach i,CC CFLAGS CPPFLAGS LDFLAGS,$(call shellexport,$i)) \
	    sh ../Build.sh -r -tpax; \
	    echo $$? >Build.rv \
	) 2>&1 | sed \
	    -e 's!conftest.c:\([0-9]*\(:[0-9]*\)*\): error:!cE(\1) -!g' \
	    -e 's!conftest.c:\([0-9]*\(:[0-9]*\)*\): warning:!cW(\1) -!g' \
	    -e 's!conftest.c:\([0-9]*\(:[0-9]*\)*\): note:!cN(\1) -!g'
	test x"$$(cat builddir/Build.rv 2>&1)" = x"0"
