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

SHELL := /bin/bash
pf := set -o pipefail

# This file is licensed under the terms of the GNU Public License.
# Maintained by Kevin Kelley <kelleyk@kelleyk.net>.
#
# Based on packaging (c) 2013 Robert Bruce Park <r@robru.ca>.
# Portions borrowed from the packaging that Rob Browning maintains for
# the Debian project and/or the modifications made by the Ubuntu
# developers for their fork of that packaging.


# Some inspiration taken from the Emacs' debian/rules file created by
# Mark Eichin, Ian Jackson, Jérôme Marant, and Rob Browning, however
# the code below was largely rewritten from scratch in 2013.


# This packaging data is intended to be usable both for building
# snapshots or for building stable release packages. Everything here
# parses debian/changelog in order to determine what kind of package
# names to use. Debian is a little bit fussy about needing
# debian/control to exist before it'll allow debian/rules to
# create it, so unfortunately we need both control and control.in
# checked into version control. Currently this branch is set up for
# snapshot builds, however if you want to package a stable release,
# all you have to do is change "emacs-snapshot" to "emacs24" in
# debian/changelog, and then run this command:
#
#    $ make -f debian/rules debian/control
#
# That will rebuild debian/control with the new package names, and
# you'll then be able to proceed with the package build as usual.


# What suffix should we append to "emacs" to make it parallel-installable?
# Generally "-snapshot", however it could be "23" or "24" as necessary.
suffix = $(shell dpkg-parsechangelog  \
		| perl -ne 's/Source: emacs// && print && exit')

DISTRIB_RELEASE = "$(shell grep DISTRIB_RELEASE /etc/lsb-release | cut -d= -f2)"
ifeq ($(shell dpkg --compare-versions "$(DISTRIB_RELEASE)" ge "16.10" && echo "yes"),yes)
  ifneq (,$(filter $(DEB_HOST_ARCH),amd64 ppc64el s390x))
    # These flags are necessary on 16.10 and later, but break builds on earlier releases (14.04, for example).
    export DEB_CFLAGS_MAINT_APPEND=-no-pie
    export DEB_LDFLAGS_MAINT_APPEND=-no-pie
    # export DEB_BUILD_MAINT_OPTIONS=hardening=-pie
  endif
endif

$(info *** Detected DISTRIB_RELEASE=$(DISTRIB_RELEASE))

# @kelleyk: This version-detection machinery is borrowed from the
# Debian/Ubuntu packaging.

# For now we assume that emacs' versioning scheme is always
# MAJOR.MINORtinyrev where MAJOR and MINOR are integers and tinyrev is
# an optional lowercase letter (or letters).  We also assume that
# upstream uses a numbering scheme that sorts in a "Debian friendly"
# way.	So far that's always been true.	 If it becomes false, some of
# the values below will have to be set manually.

# (You might imagine that a VPATH build would allow us to avoid having
#  to copy the entire source tree for each of the three builds, but it
#  turns out that the emacs build process doesn't entirely respect the
#  VPATH and modifies all kinds of files in the srcdir (e.g. *.elc,
#  *.map, etc.).

# The official upstream version defined by AC_INIT in configure.in.
upstream_ver := $(shell debian/upstream-version)
ifeq (,$(upstream_ver))
  $(error 'Unable to find upstream version number.')
endif

# This must be the version that's actually used at runtime for things
# like load-path.  It may not be the same as the upstream version
# (i.e. when you have upstream 20.5a, the functional version may still
# be 20.5), so sometimes we may have to do this by hand.
runtime_ver := $(shell $(pf); echo $(upstream_ver) | perl -pe 's/[a-z]+$$//o')
major_ver := $(shell $(pf); echo $(runtime_ver) | perl -pe 's/\..*$$//o')
minor_ver := $(shell $(pf); echo $(runtime_ver) | perl -pe 's/^[^.]*\.//o')

# @kelleyk: Adding this as a sanity check after a build where this
# wound up as the empty string.
ifeq (,$(runtime_ver))
  $(error 'Unable to find runtime version number.')
endif

# lisp paths
local_lpath := /etc/emacs
local_lpath := $(local_lpath):/usr/local/share/emacs/$(runtime_ver)/site-lisp
local_lpath := $(local_lpath):/usr/local/share/emacs/site-lisp
local_lpath := $(local_lpath):/usr/share/emacs/$(runtime_ver)/site-lisp
local_lpath := $(local_lpath):/usr/share/emacs/site-lisp

$(info *** Detected upstream_ver=$(upstream_ver))
$(info *** Detected runtime_ver=$(runtime_ver))
$(info *** Setting load-path=$(local_lpath))

# @kelleyk: It's not clear to me what this does; this variable never
#   seems to be referenced.
# # Installation local_lpath
# local_lpath_install \
#   := $(pkgdir_common)/$(subst :,:$(pkgdir_common)/,$(local_lpath))

# common configure flags
confflags += --prefix=/usr
confflags += --sharedstatedir=/var/lib
confflags += --libexecdir=/usr/lib
confflags += --localstatedir=/var/lib
confflags += --infodir=/usr/share/info
confflags += --mandir=/usr/share/man
confflags += --enable-locallisppath="$(local_lpath)"
confflags += --program-suffix="$(suffix)"
confflags += --with-modules
confflags += --with-file-notification=inotify
confflags += --with-mailutils
confflags += --with-harfbuzz
confflags += --with-json
confflags += --with-zlib

# These package names are used to create debian/control
src_pkg_name = emacs$(suffix)
gtk_pkg_name = $(src_pkg_name)
nox_pkg_name = $(gtk_pkg_name)-nox
nativecomp_pkg_name = $(gtk_pkg_name)-nativecomp

# Gtk config options
confflags_gtk += $(confflags)
confflags_gtk += --with-x=yes
confflags_gtk += --with-x-toolkit=gtk3
confflags_gtk += --with-lcms2
confflags_gtk += --with-cairo
confflags_gtk += --with-xpm=yes --with-gif=yes --with-gnutls=yes --with-jpeg=yes --with-png=yes --with-tiff=yes
ifeq ($(shell dpkg --compare-versions "$(DISTRIB_RELEASE)" gt "16.04" && echo "yes"),yes)
  # Upstream commit ae3edf0ac3 transitioned from the WebKitGTK+ API to
  # JavaScriptCore, but the version of libjavascriptcoregtk-4.0-dev in
  # 16.04 LTS (xenial) is too old.  See
  # https://github.com/kelleyk/ppa-emacs/issues/15 for details.
  confflags_gtk += --with-xwidgets
endif

# Gtk dh options
auto_gtk += --package=$(gtk_pkg_name)
auto_gtk += --builddirectory=build/gtk

# NoX config options
confflags_nox += $(confflags)
confflags_nox += --with-x=no

# NoX dh options
auto_nox += --package=$(nox_pkg_name)
auto_nox += --builddirectory=build/nox

# Gtk/nativecomp config options
confflags_nativecomp += $(confflags)
ifeq ($(shell dpkg --compare-versions "$(DISTRIB_RELEASE)" ge "20.04" && echo "yes"),yes)
  # The native compilation feature requires `libgccjit`, and 20.04 LTS
  # (focal) is the first release where the default version of GCC
  # offers that.
  #
  # This will, of course, produce `*-nativecomp` packages that don't
  # have native compilation enabled for older Ubuntu releases; we just
  # don't upload/release those.
  confflags_nativecomp += --with-native-compilation
endif

# Gtk/nativecomp dh options
auto_nativecomp += --package=$(nativecomp_pkg_name)
auto_nativecomp += --builddirectory=build/nativecomp

# These files are created from emacsVER templates
autogen_install_files :=  \
  debian/$(gtk_pkg_name).install  \
  debian/$(gtk_pkg_name).postinst  \
  debian/$(gtk_pkg_name).prerm	\
  debian/$(nox_pkg_name).install  \
  debian/$(nox_pkg_name).postinst  \
  debian/$(nox_pkg_name).prerm \
  debian/$(nativecomp_pkg_name).install	 \
  debian/$(nativecomp_pkg_name).postinst  \
  debian/$(nativecomp_pkg_name).prerm

define deb_sub
  perl -p  \
    -e "s|\@SUFFIX\@|$(suffix)|go;"  \
    -e "s|\@PKG_NAME\@|$(pkg_name)|go;"	 \
    -e "s|\@SRC_PKG_NAME\@|$(src_pkg_name)|go;"	 \
    -e "s|\@GTK_PKG_NAME\@|$(gtk_pkg_name)|go;"	 \
    -e "s|\@NOX_PKG_NAME\@|$(nox_pkg_name)|go;"	 \
    -e "s|\@NATIVECOMP_PKG_NAME\@|$(nativecomp_pkg_name)|go;"  \
      < $(1) > $(2)
endef

# Set pkg_name depending on which we are currently building.
debian/$(gtk_pkg_name).%: pkg_name := $(gtk_pkg_name)
debian/$(nox_pkg_name).%: pkg_name := $(nox_pkg_name)

# Build emacs*.{install,...} from emacsVER.{install,...}
debian/$(gtk_pkg_name).%: debian/emacsVER.%
	$(call deb_sub,$<,$@)

# Build emacs*-nox.{install,...} from emacsVER.{install,...}
debian/$(nox_pkg_name).%: debian/emacsVER.%
	$(call deb_sub,$<,$@)

# Build emacs*-nativecomp.{install,...} from emacsVER.{install,...}
debian/$(nativecomp_pkg_name).%: debian/emacsVER.%
	$(call deb_sub,$<,$@)

# Build control from control.in.
debian/%: debian/%.in debian/changelog debian/rules
	$(call deb_sub,$<,$@)

override_dh_auto_clean:
	# @kelleyk: Starting with jammy, these files cause debuild to
	# refuse to do anything; whereas with focal, this isn't
	# necessary.
	rm -f *build-deps*.{buildinfo,changes}
	dh_auto_clean $(auto_gtk)
	dh_auto_clean $(auto_nox)
	dh_auto_clean $(auto_nativecomp)

override_dh_auto_configure:
	./autogen.sh
	dh_auto_configure $(auto_gtk) -- $(confflags_gtk)
	dh_auto_configure $(auto_nox) -- $(confflags_nox)
	dh_auto_configure $(auto_nativecomp) -- $(confflags_nativecomp)

override_dh_auto_build: debian/control
	dh_auto_build $(auto_gtk)
	dh_auto_build $(auto_nox)
	NATIVE_FULL_AOT=1 dh_auto_build $(auto_nativecomp)

# Run tests, but don't allow failures to stop the build.
override_dh_auto_test:
	dh_auto_test $(auto_gtk) || true
	dh_auto_test $(auto_nox) || true
	dh_auto_test $(auto_nativecomp) || true

# By default dh_auto_install will dump both packages into debian/tmp,
# with the second one clobbering the first one, so we used --destdir to
# force installation into different places.
override_dh_auto_install: $(autogen_install_files)
	dh_auto_install $(auto_gtk) --destdir=debian/$(gtk_pkg_name)
	dh_auto_install $(auto_nox) --destdir=debian/$(nox_pkg_name)
	dh_auto_install $(auto_nativecomp) --destdir=debian/$(nativecomp_pkg_name)
#
#	Find the binaries that we need to pass to update-alternatives.
	alternatives=`ls debian/$(gtk_pkg_name)/usr/bin | xargs`  \
	  && set -x  \
	  && for f in debian/emacs*.*;	\
	  do  \
	    perl -pwi -e "s|\@ALTERNATIVES\@|$${alternatives}|go" $$f;	\
	  done

# Use of --destdir above causes the default dh_install to fail,
# because it looks for files in debian/tmp (which does not exist). So
# override it to instead delete the files we don't want
override_dh_install:
#	Strip images from NoX.
	rm -rf debian/$(nox_pkg_name)/usr/share/emacs/*/etc/images
#
#	Strip some unnecessary dirs
	rm -rf debian/*/var/
	rm -rf debian/*/usr/local
#
#	And some things lintian doesn't like
	rm -rf debian/*/usr/share/emacs/*/etc/copying.paper
	rm -rf debian/*/usr/share/emacs/*/lisp/COPYING
#
#	Identify identical files, move them into -common, and delete them
#	from the other binary packages.
	mkdir -p debian/$(src_pkg_name)-common
	diff --ignore-all-space --recursive --brief --report-identical-files  \
		debian/$(gtk_pkg_name) debian/$(nox_pkg_name) debian/$(nativecomp_pkg_name) \
		| egrep -v '(/usr/lib|/usr/bin)'  \
		| perl -ne 's/^Files (.*) and (.*) are identical/\1\n\2/ && print'  \
		| tar cpf - --files-from - --remove-files  \
		| tar xpf - --directory debian/$(src_pkg_name)-common  \
		--strip-components=2 --overwrite
#
#	Move non-byte-compiled versions of byte-compiled files into -el package.
	mkdir -p debian/$(src_pkg_name)-el
	find debian/ -name '*.elc'  \
		| perl -pe 's/(.*)\.elc/\1.el.gz/g'  \
		| tar cpf - --files-from - --remove-files --ignore-failed-read	\
		| tar xpf - --directory debian/$(src_pkg_name)-el  \
		--strip-components=2 --overwrite

%:
	dh $@ --parallel
