#!/usr/bin/make -f

DEB_HOST_ARCH_OS=$(shell dpkg-architecture -qDEB_HOST_ARCH_OS)

CC?=			gcc
EXTRA_CFLAGS=		-Wall -Wextra -Wformat -fno-strict-aliasing
EXTRA_LDFLAGS=		-Wl,--as-needed

ifneq (kfreebsd,${DEB_HOST_ARCH_OS})
ifneq (x32,${DEB_HOST_ARCH})
EXTRA_CPPFLAGS+=	-DLONG_OFF_T
endif
endif

ifneq (,$(wildcard /usr/share/dpkg/buildflags.mk))
# dpkg-dev (>= 1.16.1~)
DEB_CFLAGS_MAINT_APPEND=${EXTRA_CFLAGS}
DEB_CPPFLAGS_MAINT_APPEND=${EXTRA_CPPFLAGS}
DEB_LDFLAGS_MAINT_APPEND=${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

build: build-arch build-indep
build-arch: debian/.build_stamp
build-indep:

debian/.build_stamp:
	dh_testdir
	+for opts in '-flto=jobserver' '-fwhole-program --combine' ''; do \
		set -x; \
		${CC} ${CPPFLAGS} ${CFLAGS} $$opts ${LDFLAGS} -o pax ar.c \
		    ar_io.c ar_subs.c buf_subs.c cache.c cpio.c file_subs.c \
		    ftree.c gen_subs.c getoldopt.c options.c pat_rep.c pax.c \
		    sel_subs.c tables.c tar.c tty_subs.c; \
		test -x pax && exit 0; \
	done; echo >&2 Compiling failed.; exit 1
	echo .nr g 2 | cat - cpio.1 >debian/paxcpio.1
	echo .nr g 2 | cat - pax.1 >debian/pax.1
	echo .nr g 2 | cat - tar.1 >debian/paxtar.1
	@:>$@

clean:
	dh_testdir
	dh_clean
	-rm -f debian/.*_stamp \
	    debian/paxcpio.1 debian/pax.1 debian/paxtar.1 pax

binary-indep: build-indep

binary-arch: build-arch
	dh_testdir
	dh_testroot
	if test -x "$$(which dh_prep)"; then dh_prep; else dh_clean -k; fi
	dh_installchangelogs
	dh_installdocs
	dh_install
	dh_installman
	dh_lintian
	dh_link
	dh_strip
	dh_compress
	dh_fixperms
	dh_installdeb
	dh_shlibdeps
	dh_gencontrol
	dh_md5sums
	dh_builddeb

binary: binary-arch binary-indep

.PHONY: binary binary-arch binary-indep build build-arch build-indep clean
