#!/usr/bin/make -f

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=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_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)

CPPFLAGS := $(shell dpkg-buildflags --get CPPFLAGS)
CFLAGS := -Wall $(shell dpkg-buildflags --get CFLAGS)
LDFLAGS := $(shell dpkg-buildflags --get LDFLAGS)

ifeq ($(DEB_BUILD_GNU_TYPE), $(DEB_HOST_GNU_TYPE))
	confflags += --build=$(DEB_HOST_GNU_TYPE)
else
	confflags += --build=$(DEB_BUILD_GNU_TYPE) --host=$(DEB_HOST_GNU_TYPE)
endif

lib := libbsd0
libdbg := $(lib)-dbg
libudeb := $(lib)-udeb
libdev := libbsd-dev

config-stamp:
	dh_testdir

	dh_autoreconf
	./configure \
		CPPFLAGS="$(CPPFLAGS)" \
		CFLAGS="$(CFLAGS)" \
		LDFLAGS="$(LDFLAGS)" \
		$(confflags) \
		--disable-silent-rules \
		--prefix=/usr \
		--libdir=\$${prefix}/lib/$(DEB_HOST_MULTIARCH)
	touch config-stamp

build-indep:

build-arch: config-stamp
	dh_testdir

	$(MAKE)

build: build-indep build-arch

# Run the test suites
check-arch: build-arch
	dh_testdir

ifeq ($(DEB_BUILD_GNU_TYPE), $(DEB_HOST_GNU_TYPE))
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	$(MAKE) check
endif
endif

clean:
	dh_testdir
	dh_testroot

	[ ! -f Makefile ] || $(MAKE) distclean

	dh_autoreconf_clean
	dh_clean

install-arch: check-arch
	dh_testdir
	dh_testroot
	dh_prep
	dh_installdirs

	$(MAKE) install DESTDIR=$(CURDIR)/debian/tmp \
	                runtimelibdir=/lib/$(DEB_HOST_MULTIARCH)

binary-indep:
# Nothing to do.

binary-arch: install-arch
	dh_testdir
	dh_testroot
	dh_installchangelogs ChangeLog
	dh_installdocs
	dh_installexamples
	dh_install
	dh_link
	dh_strip --dbg-package=$(libdbg)
	dh_compress
	dh_fixperms
	dh_makeshlibs --add-udeb=$(libudeb)
	dh_installdeb
	dh_shlibdeps
	dh_gencontrol
	dh_md5sums
	dh_builddeb

binary: binary-indep binary-arch

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