#!/usr/bin/make -f

# the equivalent of "uwsgi-core --dot-h | md5sum" at runtime
abi = $(firstword $(shell echo | cat uwsgi.h - | md5sum))

# resolve supported architectures for arch-varying build-dependencies
# (in maintainer mode only: uses network and messes with control file)
ifneq (,$(DEB_MAINTAINER_MODE))
$(shell sh debian/pkgarchs.sh glusterfs-common > debian/ARCHS_glusterfs)
$(shell sh debian/pkgarchs.sh python-greenlet-dev > debian/ARCHS_greenlet)
$(shell sh debian/pkgarchs.sh openjdk-17-jdk > debian/ARCHS_openjdk17)
$(shell sh debian/pkgarchs.sh librados-dev > debian/ARCHS_rados)
$(shell sh debian/pkgarchs.sh gccgo > debian/ARCHS_gccgo)
endif
UWSGI_ARCHLISTS = glusterfs greenlet openjdk17 rados gccgo
$(foreach list,$(UWSGI_ARCHLISTS),\
	$(eval UWSGI_ARCHS_$(list) := $(shell cat debian/ARCHS_$(list))))
ifneq (,$(DEB_MAINTAINER_MODE))
debian/control::
	perl -sgpi \
	 -e 'BEGIN { %re = (' \
	 -e ' glusterfs => qr/glusterfs/,' \
	 -e ' greenlet  => qr/(gevent|greenlet)/,' \
	 -e ' openjdk17 => qr/jdk/,' \
	 -e ' rados     => qr/rados/,' \
	 -e ' gccgo     => qr/gccgo/,' \
	 -e ')}' \
	 -e 'while ( my ($$key, $$pat) = each %re ) {' \
	 -e ' my $$list = $${$$key};' \
	 -e ' s/^# autogenerated:.+\n\s+\S*$$pat.*\[\K[^\]\n]*/$$list/gm;' \
	 -e ' s/^Package:.*$$pat.*\n# autogenerated:.+\nArchitecture:\s+\K[^\n]*/$$list/gm;' \
	 -e '};' \
	 -- $(foreach list,$(UWSGI_ARCHLISTS),-$(list)='$(UWSGI_ARCHS_$(list))') \
	 -- $@
endif

# Common variables
# ================

UWSGI_ENV = CFLAGS="$(CFLAGS)" CPPFLAGS="$(CPPFLAGS)" LDFLAGS="$(LDFLAGS)"

UWSGI_BUILDER = python3 uwsgiconfig.py -v

UWSGI_SRCPLUGINS_AVAILABLE := $(sort $(notdir $(wildcard plugins/*)))
# plugins not yet ready for production use
UWSGI_SRCPLUGINS_EXPERIMENTAL = libffi libtcc router_spnego
# plugins irrelevant/unusable for Debian or built separately (by another
# dedicated source package.
UWSGI_SRCPLUGINS_ALIEN = airbrake alarm_speech matheval mongodb \
    stackless emperor_mongodb gridfs mongodblog mono php \
	stats_pusher_mongodb v8 gccgo jvm ring servlet jwsgi \
	glusterfs rados rack fiber rbthreads lua \
	python tornado asyncio greenlet gevent psgi coroae \
	pypy
UWSGI_SRCPLUGINS_DEMO = cplusplus dumbloop dummy example exception_log
UWSGI_SRCPLUGINS_UNKNOWN = legion_cache_fetch objc_gc pyuwsgi ruby19
UWSGI_SRCPLUGINS_EXCLUDE = $(UWSGI_SRCPLUGINS_ALIEN) \
	$(UWSGI_SRCPLUGINS_DEMO) $(UWSGI_SRCPLUGINS_EXPERIMENTAL) \
	$(UWSGI_SRCPLUGINS_UNKNOWN)
UWSGI_SRCPLUGINS_WANTED = $(filter-out $(UWSGI_SRCPLUGINS_EXCLUDE),\
	$(UWSGI_SRCPLUGINS_AVAILABLE))
UWSGI_SRCPLUGINS_ADDON = alarm_curl alarm_xmpp curl_cron \
	emperor_pg geoip graylog2 ldap \
	router_access sqlite3 xslt
# tun/tap is unavailable on the Hurd
# systemd is available only on linux
# tuntap plugin broken on kFreeBSD: https://github.com/unbit/uwsgi/issues/695
UWSGI_SRCPLUGINS_SKIP = \
	$(if $(filter hurd,$(DEB_HOST_ARCH_OS)),\
		tuntap) \
	$(if $(filter kfreebsd,$(DEB_HOST_ARCH_OS)),\
		tuntap) \
	$(if $(filter-out linux,$(DEB_HOST_ARCH_OS)),\
		systemd_logger)
UWSGI_SRCPLUGINS_CORE = $(filter-out \
	$(UWSGI_SRCPLUGINS_ADDON) \
	$(UWSGI_SRCPLUGINS_SKIP),\
	$(UWSGI_SRCPLUGINS_WANTED))

# Build Rules
# ===========

%:
	dh $@

override_dh_auto_clean:
	# do not call dh_auto_clean (wrongly calling make clean)
	dh_clean
	$(UWSGI_BUILDER) --clean
	find -type f -name '*.pyc' -delete
	find -type d -name __pycache__ -delete

PLUGINS := $(addsuffix _plugin.so, \
				$(addprefix build/plugins-core/,$(UWSGI_SRCPLUGINS_CORE)) \
				$(UWSGI_SRCPLUGINS_ADDON))

PLUGIN_BINARIES := $(shell grep -h ^usr/bin/uwsgi-core debian/*links \
						| cut -f5 -d'/')
PLUGIN_BINARIES_MANPAGES := $(addsuffix .1,$(addprefix debian/,$(PLUGIN_BINARIES)))

bin/uwsgi_%:
	ln -sf uwsgi-core bin/uwsgi_$*

%_plugin.so:
	$(UWSGI_ENV) $(UWSGI_BUILDER) \
		--plugin plugins/`basename $*` \
		debian/buildconf/uwsgi-plugin.ini
	if [ `dirname $@` != "." ]; then \
		mkdir -p `dirname $@` && mv `basename $@` $@; \
	fi

debian/%.1: bin/%
	help2man \
		--name 'fast (pure C), self-healing, developer-friendly WSGI server' \
		--section 1 \
		--no-info \
		$< > $@

debian/debhelper/dh_uwsgi.1: debian/debhelper/dh_uwsgi
	pod2man debian/debhelper/dh_uwsgi > debian/debhelper/dh_uwsgi.1

build/plugins-src:
	mkdir -p build
	cp -a plugins $@
	find $@ -type f -name '*.key' -or -name '*.dll' -delete

bin/uwsgi-core:
	$(UWSGI_ENV) $(UWSGI_BUILDER) --build debian/buildconf/uwsgi-core.ini

override_dh_auto_build: \
		bin/uwsgi-core debian/uwsgi-core.1 \
		$(PLUGINS) \
		$(addprefix bin/,$(PLUGIN_BINARIES)) $(PLUGIN_BINARIES_MANPAGES) \
		debian/debhelper/dh_uwsgi.1 \
		build/plugins-src

override_dh_auto_install:
	# do not call dh_auto_install (wrongly calling make install)
	dh_install

# Custom substvars
# ================

substvars-list-encode = perl -0 -F'/\s+/' -ane 'print " * ", join("\$${Newline} * ",@F)'
uwsgi-corepluginlist := $(shell echo $(UWSGI_SRCPLUGINS_CORE) | $(substvars-list-encode))

override_dh_gencontrol:
	echo 'uwsgi:Provides=uwsgi-abi-$(abi)' >> debian/uwsgi-core.substvars
	echo 'uwsgi:corepluginlist=$(uwsgi-corepluginlist)' >> debian/uwsgi-core.substvars
	dh_gencontrol -- -Vuwsgi:abi=$(abi)

# Examples
# =================
# move installed examples into subdirs by type
ex_types = conffile psgi rack router wsapi wsgi
ex_conffile = mega.xml multi.* sites.xml uwsgi.xml vassals werkzeug_strict.yml werkzeug.*
ex_rack = config.ru config2.ru fibers.*
ex_router = router.lua uwsgirouter*
ex_psgi = mojoapp.pl
ex_wsapi = *.ws
ex_wsgi = mjpeg_stream.py multiapp.py simple_app.py simple_app_wsgi2.py taskqueue.py
ex_drop = bootstrap* config*.lua config??.ru corostream.pl debug.ini
ex_drop += flaskpost.py heavytest.* info_uwsgi.php logic.ini
ex_drop += protected.ini welcome.ini welcome3.py

override_dh_installexamples:
	dh_installexamples
	set -e; \
	cd debian/uwsgi-core/usr/share/doc/uwsgi-core/examples; \
	$(foreach type, $(ex_types),mkdir $(type); mv -t $(type) $(ex_$(type));) \
	rm $(ex_drop)

override_dh_compress:
	dh_compress $(foreach ext, \
		.ini .lua .pl .png .psgi .py .ru .ws .xml .yml .java .rb .c, -X$(ext))

# Build time checks
# =================

override_dh_auto_test:
	find debian \
		-type f -not -empty -regextype egrep \
		-regex '.*(postinst|prerm|rtupdate|init\.d).*' \
		-exec shellcheck -e SC1090,SC1091,SC2034,SC2043 -s sh {} +
	shellcheck -e SC1091,SC2001,SC2034,SC2162 -s bash debian/uwsgi-files/init/*
