#!/usr/bin/make -f

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

LC_ALL:=C
export LC_ALL
TZ:=UTC
export TZ

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

ifneq (,$(wildcard /usr/share/dpkg/architecture.mk))
include /usr/share/dpkg/architecture.mk
endif

ifneq (,$(wildcard /usr/share/dpkg/buildtools.mk))
DPKG_EXPORT_BUILDTOOLS:=1
include /usr/share/dpkg/buildtools.mk
else
# is ${CC} defined anywhere (other than implicit rules?)
ifneq (,$(findstring $(origin CC),default undefined))
# no - then default to gcc (or cross-gcc)
DEB_BUILD_ARCH?=$(shell dpkg-architecture -qDEB_BUILD_ARCH)
DEB_HOST_ARCH?=$(shell dpkg-architecture -qDEB_HOST_ARCH)
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
endif

OUR_CPPFLAGS:=
OUR_CFLAGS:=
OUR_LDFLAGS:=

ifneq (,$(filter debug,${DEB_BUILD_OPTIONS}))
OUR_CFLAGS+=	-Og -g3
endif

OUR_CFLAGS+=	-Wall -Wextra -Wformat
# for now
OUR_CFLAGS+=	-Wno-unused-variable
OUR_CFLAGS+=	-Wno-unused-parameter
OUR_CFLAGS+=	-Wno-unused-but-set-variable
# not fully protoised
OUR_CFLAGS+=	-std=gnu99
# but go towards
OUR_CFLAGS+=	-Wstrict-prototypes

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

%:
	dh $@ -Snone

execute_before_dh_auto_clean:
	dh_testdir
	-rm -rf builddir

override_dh_auto_build:
	dh_testdir
	-rm -rf builddir
	mkdir builddir
	cd builddir && ln -s ../* . && xmkmf && exec make \
	    DEFINES=$(call shellescape,${CPPFLAGS}) \
	    CDEBUGFLAGS=$(call shellescape,${CFLAGS}) \
	    CXXDEBUGFLAGS=$(call shellescape,${CXXFLAGS}) \
	    EXTRA_LDOPTIONS=$(call shellescape,${LDFLAGS})
