#!/usr/bin/make -f
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

# resolve DEB_VERSION_UPSTREAM_REVISION DEB_DISTRIBUTION
include /usr/share/dpkg/pkg-info.mk

# resolve DEB_BUILD_ARCH_OS DEB_HOST_MULTIARCH
include /usr/share/dpkg/architecture.mk

# generate documentation unless nodoc requested
CHANGELOGS_stem = ChangeLogs/ChangeLog-certified-$(firstword $(subst ~, ,$(DEB_VERSION_UPSTREAM)))
DOCS_stem = README SECURITY
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
CHANGELOGS = $(CHANGELOGS_stem:=.html) $(CHANGELOGS_stem:=.txt)
DOCS = $(DOCS_stem:=.html) $(DOCS_stem:=.txt)
MANPAGES = debian/build/dh_asterisk.1
endif

# Starting with dpkg-dev >= 1.16.1.1 you can use the new buildflags.mk file
# to set all *FLAGS
# When building programs that handle untrusted data
# (parsers, network listeners, etc.),
#  or run with elevated privileges (PAM, X, etc.),
#  please enable "PIE" and "BINDNOW" in the build.
#  The "all" option enables "PIE" and "BINDNOW" and future hardening flags

export deb_systemdsystemunitdir = $(shell pkg-config --variable=systemdsystemunitdir systemd | sed s,^/,,)

%:
	dh $@

%.html: %.md
	cmark-gfm $< > $@

%.txt: %.md
	cmark-gfm --to plaintext $< > $@

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
DPKG_EXPORT_BUILDFLAGS = 1
ifeq (,$(filter noopt,$(DEB_BUILD_OPTIONS)))
DEB_CFLAGS_MAINT_STRIP = -O2
DEB_CFLAGS_MAINT_APPEND = -O3 -fno-partial-inlining
endif
include /usr/share/dpkg/buildflags.mk

# Sanity check for a stable release:
SAVED_ABI_HASH = 1fb7f5c06d7a2052e38d021b3d8ca151

export DEB_HOST_GNU_TYPE  ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
export DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
export DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)

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

export PROC := $(shell dpkg-architecture -qDEB_BUILD_GNU_CPU)

# don't let asterisk mess with build flags
BUILDFLAGS += AST_FORTIFY_SOURCE= DEBUG= OPTIMIZE=

# show full gcc arguments unless DEB_BUILD_OPTIONS=terse
ifeq (,$(filter terse,$(DEB_BUILD_OPTIONS)))
BUILDFLAGS += NOISY_BUILD=yes
endif

BUILDFLAGS += ASTDATADIR=/var/lib/asterisk ASTVARRUNDIR=/run/asterisk

ifneq (,$(findstring debug,$(DEB_BUILD_OPTIONS)))
	ENABLE_DEBUG += --enable-dev-mode
endif
ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS)))
	INSTALL_PROGRAM += -s
endif

# Addons
# Removed since Asterisk 19
#ADDONS_ENABLE += app_mysql cdr_mysql

# Non core modules
# Applications
# Removed since Asterisk 21
#ADDONS_ENABLE += app_macro
ADDONS_ENABLE = app_alarmreceiver app_amd app_attended_transfer app_blind_transfer app_chanisavail app_dictate app_externalivr app_festival app_jack app_minivm app_morsecode app_mp3 app_sms app_test app_waitforring app_waitforsilence app_zapateller app_adsiprog app_getcpeid
# Applications for FreePBX
ADDONS_ENABLE += app_broadcast app_flash app_if app_sf app_signal app_meetme
# CDR
ADDONS_ENABLE += cdr_csv cdr_odbc  cdr_radius cdr_sqlite3_custom cdr_tds
# CEL
ADDONS_ENABLE += cel_radius cel_sqlite3_custom cel_tds
# Channel Drivers
# Removed since Asterisk 21
#ADDONS_ENABLE += chan_alsa chan_mgcp chan_skinny chan_sip
ADDONS_ENABLE += chan_dahdi chan_mobile chan_ooh323 chan_console chan_unistim
# Codec Translators
ADDONS_ENABLE += codec_dahdi
# Codec Translators External
ADDONS_ENABLE += codec_opus codec_silk codec_siren7 codec_siren14
# Codec Opus Open Source
#ADDONS_ENABLE += codec_opus_open_source
# Dialplan Functions
ADDONS_ENABLE += func_frame_trace func_pitchshift
# Dialplan Functions for FreePBX
ADDONS_ENABLE += func_evalexten func_export func_json
# Format Interpreters
ADDONS_ENABLE += format_mp3 format_ogg_speex format_vox
# PBX Modules
ADDONS_ENABLE += pbx_ael pbx_dundi pbx_lua pbx_realtime
# Resource Modules
ADDONS_ENABLE += res_config_mysql res_timing_pthread res_phoneprov res_pjsip_history res_pjsip_phoneprov_provider res_hep res_hep_pjsip res_hep_rtcp
# Resource Modules for FreePBX
# Removed from Asterisk 21
#ADDONS_ENABLE += res_pktccops res_monitor
ADDONS_ENABLE += res_calendar res_calendar_caldav res_calendar_ews res_calendar_exchange res_calendar_icalendar res_chan_stats res_cliexec res_config_ldap res_digium_phone res_endpoint_stats res_pjsip_aoc res_pjsip_stir_shaken res_smdi res_snmp res_statsd res_stir_shaken res_timing_dahdi
# Utilities
ADDONS_ENABLE += aelparse smsq
# Compiler flags
ADDONS_ENABLE += TEST_FRAMEWORK
# Disabled addons
ADDONS_DISABLE = BUILD_NATIVE
# Sounds
ADDONS_DISABLE += CORE-SOUNDS-EN-GSM
# MOH
ADDONS_DISABLE += MOH-OPSOUND-WAV
ifneq (,$(findstring debug,$(DEB_BUILD_OPTIONS)))
ADDONS_ENABLE += BETTER_BACKTRACES DEBUG_THREADS
endif

# howto check selected options:
# menuselect/menuselect --list-options menuselect.makeopts | grep <modulename>
# make menuselect # for ncurses based terminal

include /usr/share/dpkg/pkg-info.mk
DEBVERSION:=$(DEB_VERSION)
DEB_NOEPOCH_VERSION:=$(shell echo $(DEBVERSION) | cut -d':' -f 2)

# make sure we have 'fetch' . We need to have either wget or fetch
# on the system. However it is generally not a good idea to actually
# get remote tarballs at build time. So if neither wget nor fetch
# happen to be installed, the configure script will find a dummy
# fetch script that always returns an error.
FETCH_ENV = PATH=$$PATH:$(CURDIR)/debian/dummyprogs

# resolve if release is experimental
EXP_RELEASE := $(if $(shell dpkg-parsechangelog | grep '^Distribution: \(experimental\|UNRELEASED\)'),exp)

override_dh_autoreconf:
	if [ ! -r configure.debian_sav -a -r configure ]; then cp -a configure configure.debian_sav; fi
	[ -f .version.debian_sav ] || cp -a .version .version.debian_sav
	echo $(DEB_NOEPOCH_VERSION) > .version
	dh_autoreconf -- ./bootstrap.sh

# Make sure the configure script gets an CFLAGS parameter. Otherwise
# it will build with -march=native
# Pass CPPFLAGS in the CFLAGS as otherwise the build system will
# ignore them.
CFLAGS += $(CPPFLAGS)
LDFLAGS += -Wl,--as-needed

override_dh_auto_configure:
	chmod 755 $(CURDIR)/debian/dummyprogs/fetch
	TMPDIR="$(CURDIR)/debian" $(FETCH_ENV) dh_auto_configure -- \
		--disable-asteriskssl \
		--with-gsm \
		--with-pjproject-bundled \
		$(if $(EXP_RELEASE),,--without-sdl) \
		$(if $(findstring debug,$(DEB_BUILD_OPTIONS)),--enable-dev-mode) \
		|| { cat config.log; exit 1; }

execute_before_dh_auto_build:
	$(MAKE) menuselect.makeopts BUILD_CFLAGS="$(CFLAGS)" BUILD_LDFLAGS="$(LDFLAGS)"
	for module in $(ADDONS_ENABLE); do menuselect/menuselect --enable $$module menuselect.makeopts; done
	for module in $(ADDONS_DISABLE); do menuselect/menuselect --disable $$module menuselect.makeopts; done

override_dh_auto_build:
	$(FETCH_ENV) dh_auto_build -- $(BUILDFLAGS)

execute_after_dh_auto_build: $(DOCS) $(CHANGELOGS) $(MANPAGES)
	# Sanity check: don't break the ABI for modules:
#	@abi_hash=$$(awk -F'"' '/AST_BUILDOPT_SUM/ {print $$2}' \
#	  include/asterisk/buildopts.h); \
#	if [ "$$abi_hash" != "$(SAVED_ABI_HASH)" ]; then \
#		echo "Debian packaging problem: ABI checksum changed."; \
#		echo "  Was: $(SAVED_ABI_HASH)"; \
#		echo "  Now: $$abi_hash"; \
#		echo "Check include/asterisk/buildopts.h"; \
#		[ -n "$(EXP_RELEASE)" ] || exit 1; \
#	fi

SND_FILE=asterisk-core-sounds-en-gsm-1.4.20.tar.gz
execute_before_dh_clean:
	[ ! -r sounds/$(SND_FILE) ] || mv sounds/$($SND_FILE) debian/
	GREP=grep AWK=awk $(MAKE) distclean
	[ ! -r debian/$(SND_FILE) ] || mv debian/$(SND_FILE) sounds/

	[ ! -f .version.debian_sav ] || mv .version.debian_sav .version
	[ ! -f configure.debian_sav ] || mv configure.debian_sav configure
	[ ! -f third-party/pjproject/pjproject-${PJVER}.tar.bz2.md5.debian_sav ] \
	  || mv third-party/pjproject/pjproject-${PJVER}.tar.bz2.md5.debian_sav \
	  third-party/pjproject/pjproject-${PJVER}.tar.bz2.md5

	if [ ! -d third-party/pjproject/source ]; then \
		mkdir third-party/pjproject/source; \
	fi
	if [ ! -d third-party/jansson/source ]; then \
		mkdir third-party/jansson/source; \
	fi
	if [ -d third-party/jansson/dest ]; then \
		rm -r third-party/jansson/dest; \
	fi

override_dh_gencontrol:
	AST_BUILDOPT_SUM=`grep AST_BUILDOPT_SUM include/asterisk/buildopts.h  | sed -e 's/.\+ "\(.\+\)\"/\1/g'`; \
		dh_gencontrol -- -Vasterisk:ABI=$$AST_BUILDOPT_SUM

REMOVED_PROTO_CONFS = dundi mgcp skinny unistim
REMOVED_PROTO_FILES = $(REMOVED_PROTO_CONFS:%=$(CURDIR)/debian/tmp/etc/asterisk/%.conf)
SUBPACKS_EXTRA = ooh323 mysql mp3
ifeq (linux,$(DEB_BUILD_ARCH_OS))
SUBPACKS_EXTRA += dahdi digium mobile tests
endif
SUBPACKS_EXTRA_DIRS = $(SUBPACKS_EXTRA:%=$(CURDIR)/debian/asterisk-cert-%)
SUBPACKS_EXTRA_DIRS_MOD = $(SUBPACKS_EXTRA_DIRS:%=%/usr/lib/$(DEB_HOST_MULTIARCH)/asterisk/modules)

override_dh_auto_install:
	$(FETCH_ENV) dh_auto_install -- $(BUILDFLAGS) -j1 config samples install-headers

execute_after_dh_auto_install:
	cp -a configs $(CURDIR)/debian/tmp/var/lib/asterisk/conf
	# copying missing headers and modules
	mkdir -p $(CURDIR)/debian/tmp/usr/include/asterisk
	cp include/asterisk.h $(CURDIR)/debian/tmp/usr/include
	cp -a include/asterisk $(CURDIR)/debian/tmp/usr/include
	cp addons/chan_ooh323.so addons/format_mp3.so addons/chan_mobile.so $(CURDIR)/debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/asterisk/modules
	cp addons/res_config_mysql.so $(CURDIR)/debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/asterisk/modules
	$(RM) -f $(REMOVED_PROTO_FILES)
	mkdir -p $(CURDIR)/debian/tmp/usr/bin/
	mkdir -p $(CURDIR)/debian/tmp/usr/share/man/man1
	mkdir -p $(CURDIR)/debian/tmp/usr/share/dahdi/span_config.d
	mkdir -p $(CURDIR)/debian/tmp/$(deb_systemdsystemunitdir)
	test "$(deb_systemdsystemunitdir)" != "lib/systemd/system" && mv debian/tmp/lib/systemd/system/* debian/tmp/$(deb_systemdsystemunitdir)/ || true
	rmdir --ignore-fail-on-non-empty --parents $(CURDIR)/debian/tmp/lib/systemd/system
	cp -a debian/asterisk-config-custom $(CURDIR)/debian/tmp/usr/bin/
	cp -a debian/50-asterisk $(CURDIR)/debian/tmp/usr/share/dahdi/span_config.d/
	$(RM) $(CURDIR)/debian/tmp/usr/sbin/conf2ael
	$(RM) $(CURDIR)/debian/tmp/usr/sbin/muted
	$(RM) $(CURDIR)/debian/tmp/usr/sbin/streamplayer
	$(RM) $(CURDIR)/debian/tmp/usr/sbin/stereorize
	$(RM) $(CURDIR)/debian/tmp/usr/sbin/hashtest*
	$(RM) $(CURDIR)/debian/tmp/usr/sbin/refcounter
	$(RM) $(CURDIR)/debian/tmp/var/lib/asterisk/moh/.asterisk-moh-opsound-wav-2.03
	$(RM) $(CURDIR)/debian/tmp/var/lib/asterisk/sounds/en/.asterisk-core-sounds-en-gsm-1.6.1

# hier werden alle Module gelöscht, die in separaten Paketen liegen
execute_after_dh_install-arch:
	extra_packs=$$(find $(SUBPACKS_EXTRA_DIRS_MOD) -name '*.so' -printf '%f\n');\
	  cd debian/asterisk-cert-modules/usr/lib/$(DEB_HOST_MULTIARCH)/asterisk/modules \
	  && rm -f $$extra_packs

execute_after_dh_fixperms:
	# should follow dh_fixperms; asterisk configurations may contain
	# sensitive information, such as passwords
	if [ -d $(CURDIR)/debian/asterisk-cert-config ]; then \
		chmod o-rwx $(CURDIR)/debian/asterisk-cert-config/etc/asterisk/*; \
		chmod o+rx,g+w  $(CURDIR)/debian/asterisk-cert-config/etc/asterisk/manager.d; \
	fi

override_dh_installdocs:
	# ohne den Parameter --all, weil dieser folgende Warnung ausgibt:
	# warning: Not using auto-detected asterisk-cert as main doc package for asterisk-cert-doc: With -A/--all, this would cause file-conflicts.
	dh_installdocs -- $(DOCS)
	# Für das Paket asterisk-cert-doc wurde durch obigen Befehl den falschen Paketnamen gewählt, daher dieses Verzeichnis löschen:
	$(RM) -r $(CURDIR)/debian/asterisk-cert-doc/usr/share/doc/asterisk-cert
	# das richtige Verzeichnis wird mit folgendem Befehl erstellt
	dh_installdocs -pasterisk-cert-doc --doc-main-package=asterisk-cert-doc

override_dh_installchangelogs:
	dh_installchangelogs -- $(CHANGELOGS)

override_dh_installinit:
	dh_installinit --name asterisk

override_dh_installlogrotate:
	dh_installlogrotate --name asterisk

# build manpages
debian/build/dh_asterisk.1: debian/build/%.1: debian/debhelper/dh_asterisk
	mkdir --parents debian/build
	pod2man --center="Asterisk packaging helper tools" \
		--release="asterisk $(DEB_VERSION_UPSTREAM_REVISION)" \
		$< $@
