#!/usr/bin/make -f

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

DEB_BUILD_ARCH=$(shell dpkg-architecture -qDEB_BUILD_ARCH)
DEB_HOST_ARCH=$(shell dpkg-architecture -qDEB_HOST_ARCH)
DEB_BUILD_GNU_TYPE=$(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
DEB_HOST_GNU_TYPE=$(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)

# 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})
CC=			${DEB_HOST_GNU_TYPE}-gcc
else
CC=			gcc
endif
endif

EXTRA_CFLAGS=		-Wall -Wextra -Wformat
EXTRA_CPPFLAGS=		-DUSE_LIBBSD
EXTRA_LDFLAGS=		-Wl,--as-needed

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

clean:
	dh_testdir
	dh_testroot
	test \! -f Makefile || $(MAKE) distclean
	-rm -f build-stamp config.log y.tab.c
	-rm -rf DESTDIR
	dh_clean

build-arch: build-stamp
build-indep:

CONFIGURE_ARGS+=	--prefix=/usr
CONFIGURE_ARGS+=	--sysconfdir=/etc/openntpd
CONFIGURE_ARGS+=	--mandir=\$${prefix}/share/man
CONFIGURE_ARGS+=	--build ${DEB_BUILD_GNU_TYPE}
CONFIGURE_ARGS+=	--host ${DEB_HOST_GNU_TYPE}
ifeq (,$(findstring nostrip,${DEB_BUILD_OPTIONS}))
CONFIGURE_ARGS+=	--disable-strip
endif
CONFIGURE_ARGS+=	--enable-pie
CONFIGURE_ARGS+=	--with-adjtimex
CONFIGURE_ARGS+=	--with-privsep-user=ntpd
CONFIGURE_ARGS+=	--with-privsep-path=/var/run/openntpd
CONFIGURE_ARGS+=	--with-mantype=doc

build-stamp:
	dh_testdir
	-rm -f y.tab.c
	env $(foreach i,CC CFLAGS CPPFLAGS LDFLAGS,$(call shellexport,$i)) \
	    LIBS=-lbsd ./configure ${CONFIGURE_ARGS}
	$(MAKE)
	@:>$@

binary-arch:
	dh_testdir
	dh_testroot
	if test -x "$$(which dh_prep)"; then dh_prep; else dh_clean -k; fi
	$(MAKE) install DESTDIR="$$(pwd)/DESTDIR"
	dh_installchangelogs ChangeLog
	dh_installdocs
	dh_install
	ln -sf ntpd debian/openntpd/usr/sbin/openntpd
	dh_installinit
	dh_installinit --name=ntp --update-rcd-params="defaults 23"
	dh_installman
	dh_link
	dh_strip
	dh_compress
	ln -sf ntpd.8.gz debian/openntpd/usr/share/man/man8/openntpd.8.gz
	dh_fixperms
	chmod +x debian/openntpd/etc/cron.daily/ntp
	chmod +x debian/openntpd/etc/network/if-up.d/*
	dh_installdeb
	dh_shlibdeps
	dh_gencontrol
	# Multi-Arch in a sarge compatible way
	printf '/^Architecture: /a\n%s\n.\nw\nq\n' 'Multi-Arch: foreign' | \
	    ed -s debian/openntpd/DEBIAN/control
	dh_md5sums
	dh_builddeb -- -Zgzip -z9

binary-indep:

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