#!/usr/bin/make -f

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

DEB_HOST_ARCH_OS?=$(shell dpkg-architecture -qDEB_HOST_ARCH_OS)

DEB_CFLAGS_MAINT_APPEND+=	-Wall -Wformat
DEB_CPPFLAGS_MAINT_APPEND+=	-include /usr/include/bsd/bsd.h
DEB_CPPFLAGS_MAINT_APPEND+=	-idirafter /usr/include/bsd
DEB_LDFLAGS_MAINT_APPEND=	-Wl,--as-needed

# not yet (needs to be checked upstream)
DEB_CFLAGS_MAINT_APPEND+=	-Wno-unused-but-set-variable
DEB_CFLAGS_MAINT_APPEND+=	-Wno-unused-result

DEB_BUILD_MAINT_OPTIONS=hardening=+all
include /usr/share/dpkg/buildflags.mk
include /usr/share/dpkg/buildtools.mk

# should be in libbsd
DEFS+=	-D'__IDSTRING(x,y)=static const char x[] __attribute__((__used__)) = y'
DEFS+=	-D'__KERNEL_RCSID(x,y)=__IDSTRING(kernelrcsid_ \#\# x,y)'
DEFS+=	-D'__dead=__attribute__((__noreturn__))'
DEFS+=	-D'_DIAGASSERT(x)='

# is in libbsd, but not all versions: Debian #547399
ifeq ($(shell fgrep -ch __RCSID \
    /usr/include/bsd/cdefs.h /usr/include/bsd/sys/cdefs.h \
    2>/dev/null),0)
DEFS+=	-D'__RCSID(x)=__IDSTRING(rcsid,x)'
endif

DEFS+=	-D'bswap16=__bswap_16'
DEFS+=	-D'bswap32=__bswap_32'
DEFS+=	-D'bswap64=__bswap_64'
DEFS+=	-DHAVE_STRUCT_STATVFS_F_IOSIZE=0
DEFS+=	-DHAVE_STRUCT_STAT_ST_MTIMENSEC=0
DEFS+=	-DHAVE_STRUCT_STAT_ST_FLAGS=0
DEFS+=	-DHAVE_STRUCT_STAT_ST_GEN=0

BMAKE_FLAGS:=	BSDSRCDIR="$$_topdir/builddir"
BMAKE_FLAGS+=	DEBIAN=Yes
# disable -Werror for package build (comment this out if developing)
BMAKE_FLAGS+=	NOGCCERROR=Yes

%:
	dh $@ --builddirectory=builddir

override_dh_auto_build-arch:
	dh_testdir
	-rm -rf builddir
	mkdir builddir
	cp -r src/* builddir/
ifeq (${DEB_HOST_ARCH_OS},hurd)
	mkdir -p builddir/usr.sbin/makefs/sys
	:>builddir/usr.sbin/makefs/sys/mount.h
endif
	# bmake in Debian is pretty buggy
	+_topdir=$$(pwd); cd builddir/usr.sbin/makefs; \
	 for opts in '-flto=jobserver' ''; do \
		set -x; \
		$(foreach i,CC CFLAGS LDFLAGS,$(call shellexport,$i)); \
		CPPFLAGS=$(call shellescape,${CPPFLAGS} ${DEFS}); \
		CFLAGS="$$CFLAGS $$opts"; \
		LDFLAGS="$$CFLAGS $$LDFLAGS"; \
		export LC_ALL=C CC CFLAGS CPPFLAGS LDFLAGS; \
		bmake ${BMAKE_FLAGS} makefs || continue; \
		test -x makefs && exit 0; \
	done; echo >&2 Compiling failed.; exit 1
	@:>$@

override_dh_auto_clean:
	dh_testdir
	-rm -rf builddir
