#!/usr/bin/make -f

DH_VERBOSE=1

# List of architectures where jemalloc is not available
DISABLE_JEMALLOC_ARCH_LIST := hppa m68k

# Explicitly initialize a variable to select architecture, unless it has been
# defined before.  This is compared against the DISABLE_*_LIST variables later
# in this makefile
DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)

# Set local state dir for FHS
LOCAL_CONFIGURE_FLAGS  = --localstatedir=/var/lib --libdir=/usr/lib

ifneq ($(filter $(DEB_HOST_ARCH),$(DISABLE_JEMALLOC_ARCH_LIST)),)
LOCAL_CONFIGURE_FLAGS += --disable-jemalloc
endif

VARNISHD_ABI = $(shell \
	printf '\#include "vcs_version.h"\nVCS_Version\n' | \
	cpp - -Iinclude | \
	tail -1 | \
	tr -d '"')

VARNISHD_VRT = $(shell \
	printf '\#include "vdef.h"\n\#include "vrt.h"\n%s.%s\n' \
		VRT_MAJOR_VERSION VRT_MINOR_VERSION | \
	cpp - -Iinclude | \
	tail -1 | \
	tr -c -d '[0-9.]')

# Main build rule, leave everything to debhelper
%:
	dh $@ --parallel --with systemd

ifeq (,$(filter test,$(LOCAL_BUILD_OPTIONS)))
# Disable automated build tests
override_dh_auto_test:
endif

# Override to add local configure flags
override_dh_auto_configure:
	dh_auto_configure -- $(LOCAL_CONFIGURE_FLAGS)

override_dh_auto_install:
	dh_auto_install -a
	install -d debian/tmp/etc/varnish
	install -T -m 0644 etc/example.vcl debian/tmp/etc/varnish/default.vcl
	@ # Remove .la files
	@ # (See http://wiki.debian.org/ReleaseGoals/LAFileRemoval)
	find $(CURDIR)/debian/ -name \*.la -delete
	@ # Nuke the static libs too
	find $(CURDIR)/debian -name \*.a -delete

override_dh_install-arch:
	dh_install -a --fail-missing
	@ # Override to add the "varnishreload" script
	install -o root -g root -m 755 \
		$(CURDIR)/debian/varnishreload \
		$(CURDIR)/debian/varnish/usr/sbin/varnishreload

override_dh_installdocs:
# In 4.0 the built docs need to be copied to the current/4.1 location.
	test -d doc/html || cp -pr doc/sphinx/build/html doc/html
	dh_installdocs


override_dh_gencontrol:
	echo "varnishd:ABI=varnishd-abi-$(VARNISHD_ABI)" >> debian/substvars
	echo "varnishd:VRT=varnishd-vrt (= $(VARNISHD_VRT))" >> debian/substvars

	if [ -n "$$DEBIAN_OVERRIDE_BINARY_VERSION" ]; then \
 		dh_gencontrol -- -Tdebian/substvars -v$$DEBIAN_OVERRIDE_BINARY_VERSION; \
	else \
		dh_gencontrol -- -Tdebian/substvars; \
	fi

override_dh_systemd_enable:
	dh_systemd_enable -pvarnish --name=varnish varnish.service
	dh_systemd_enable -pvarnish --no-enable varnishncsa.service

override_dh_systemd_start:
	dh_systemd_start -pvarnish varnish.service
	dh_systemd_start -pvarnish --no-start varnishncsa.service

override_dh_compress:
	dh_compress -X/usr/share/doc/varnish-doc/html

override_dh_strip:
	dh_strip --keep-debug -Xvarnish -Xlibvmod
