#!/usr/bin/make -f
# -*- makefile -*-

## use hardening some flags
DPKG_EXPORT_BUILDFLAGS = 1
DEB_BUILD_MAINT_OPTIONS=hardening=+format,-fortify,+stackprotector,+relro
export DEB_BUILD_MAINT_OPTIONS
include /usr/share/dpkg/buildflags.mk

## only link what is needed
LDFLAGS+=-Wl,--as-needed

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

archconfflags :=

ifeq ($(DEB_HOST_ARCH_OS),linux)
  archconfflags += --enable-alsa
else
  archconfflags += --disable-alsa
endif
archconfflags += --enable-jack

ifeq ($(DEB_HOST_ARCH_OS),kfreebsd)
  CFLAGS+=-D__BSD_VISIBLE
endif

## set timestamp for reproducible builds
DEB_VERSION:=$(shell dpkg-parsechangelog -SVersion)
BUILD_DATE:=$(shell date -u -d "$$(dpkg-parsechangelog -SDate)" +"%Y/%m/%d at %H:%M:%S UTC")
VERSION_CPPFLAGS ="-DPD_TIMESTAMP_STRING='\"compiled for Debian ($(DEB_VERSION)) on $(BUILD_DATE)\"' $(CPPFLAGS)"

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

%:
	dh $@ --with autoreconf

override_dh_autoreconf:
	mkdir -p m4/generated
	dh_autoreconf

override_dh_auto_configure:
	dh_auto_configure -- \
		--program-transform-name='s/pd$$/puredata/' \
		--libdir=/usr/lib/ \
		$(archconfflags) \
		CFLAGS="$(CFLAGS)" LDFLAGS="$(LDFLAGS)"

override_dh_auto_build: debian/gui-plugins/pd-gui-plugin.1
	make CPPFLAGS=$(VERSION_CPPFLAGS)

debian/gui-plugins/pd-gui-plugin.1: debian/gui-plugins/pd-gui-plugin
	help2man -N -n "enable or disable a Pd GUI plugin" $< > $@

override_dh_install:
	find debian/tmp -type f -name "pd.pc" -exec \
		sed -e 's|^Libs: .*|Libs:|' -e 's| -fPIC||' -i {} +
	dh_install -X "*.la" -X "LICENSE.txt"

override_dh_auto_clean:
	-rm -f debian/gui-plugins/pd-gui-plugin.1
	dh_auto_clean

override_dh_installchangelogs:
	dh_installchangelogs src/CHANGELOG.txt

override_dh_fixperms:
	dh_fixperms
ifneq (,$(findstring puredata-extra, $(shell dh_listpackages)))
	find debian/puredata-extra/ -type f -name "*.pd_linux" -exec \
		chmod 0644 {} +
endif
ifneq (,$(findstring puredata-gui, $(shell dh_listpackages)))
	find debian/puredata-gui/ -type f -name "pkg_mkIndex.tcl" -exec \
		chmod 0755 {} +
endif

override_dh_shlibdeps:
	dh_shlibdeps
ifneq (,$(findstring puredata-extra, $(shell dh_listpackages)))
	find debian/puredata-extra/ -type f -name "*.pd_linux" -exec \
		dpkg-shlibdeps -Tdebian/puredata-extra.substvars {} +
endif

override_dh_strip:
	dh_strip
ifneq (,$(findstring puredata-extra, $(shell dh_listpackages)))
	find debian/puredata-extra/ -type f -name "*.pd_linux" -exec \
		strip --remove-section=.comment --remove-section=.note --strip-unneeded {} +
endif

override_dh_compress:
	dh_compress -X.pd -X.wav -X.aiff -X.txt
