#!/usr/bin/make -f

include /usr/share/cdbs/1/class/python-module.mk
include /usr/share/cdbs/1/rules/debhelper.mk

# 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_PLUGIN_PACKAGES = $(filter uwsgi-plugin-%,$(DEB_PACKAGES))

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))

# Package-specific variables
# ==========================

DEB_COMPRESS_EXCLUDE_uwsgi-core = .ini .lua .pl .png .psgi .py .ru .ws .xml \
                                  .yml
DEB_COMPRESS_EXCLUDE_uwsgi-extra = .class .java .rb .c

DEB_DH_STRIP_ARGS_ALL := $(strip $(subst COND,(<< 2.0.26-3~),\
 --dbgsym-migration='uwsgi-dbg COND'))

DEB_INSTALL_DOCS_ALL += $(DEB_SRCDIR)/CONTRIBUTORS

# Rules
# =====

clean::
	$(UWSGI_BUILDER) --clean
	find -type f -name '*.pyc' -delete
	find -type d -name __pycache__ -delete
	rm -f debian/stamp-*

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

# uwsgi-core package
# ------------------

substvars-list-encode = perl -0 -F'/\s+/' -ane 'print " * ", join("\$${Newline} * ",@F)'
uwsgi-corepluginlist := $(shell echo $(UWSGI_SRCPLUGINS_CORE) | $(substvars-list-encode))
build/uwsgi-core:: bin/uwsgi-core
bin/uwsgi-core: $(addprefix build/plugins-core/,$(addsuffix _plugin.so, $(UWSGI_SRCPLUGINS_CORE)))
	$(UWSGI_ENV) $(UWSGI_BUILDER) --build debian/buildconf/uwsgi-core.ini

install/uwsgi-core::
	echo 'uwsgi:Provides=uwsgi-abi-$(abi)' >> debian/$(cdbs_curpkg).substvars
	echo 'uwsgi:corepluginlist=$(uwsgi-corepluginlist)' >> debian/$(cdbs_curpkg).substvars

# 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
binary-post-install/uwsgi-core::
	set -e; \
	cd debian/$(cdbs_curpkg)/usr/share/doc/$(cdbs_curpkg)/examples; \
	$(foreach type, $(ex_types),mkdir $(type); mv -t $(type) $(ex_$(type));) \
	rm $(ex_drop)

install/uwsgi-core:: debian/uwsgi-core.1

# uwsgi-plugin-% packages
# -----------------------

# setup hook for building plugins
$(patsubst %,build/%,$(UWSGI_PLUGIN_PACKAGES)):: \
 build/uwsgi-plugin-%: \
 bin/uwsgi-core debian/stamp-uwsgi-plugin-%

$(patsubst %,debian/stamp-%,$(UWSGI_PLUGIN_PACKAGES)): \
 debian/stamp-uwsgi-plugin-%: $(addsuffix _plugin.so,$(UWSGI_SRCPLUGINS_ADDON))
	touch $@

$(patsubst %,install/%,$(UWSGI_PLUGIN_PACKAGES)):: \
 install/uwsgi-plugin-%: $(PLUGIN_BINARIES_MANPAGES)

ifeq (,$(findstring nocheck,$(DEB_BUILD_OPTIONS)))
common-build-indep:: debian/test-shellcheck
endif
debian/test-shellcheck:
	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/*
	touch $@
clean::
	rm -f debian/test-shellcheck

# source package
# --------------

build/uwsgi-src:: build/plugins-src

# Generate manpages during build
common-post-build-arch:: debian/stamp-manpage-build
debian/stamp-manpage-build: debian/debhelper/dh_uwsgi.1
	touch $@
