#!/usr/bin/make -f

# DEB_BUILD_OPTIONS supported:
#   noopt       Compile with gcc -O0 rather than -O2
#   nostrip     Do not strip binaries and libraries
#   debug       Enable additional debug support
#   nocheck     Skip test suites (synonym 'notest')
#   with-javahl, no-javahl |
#   with-apache, no-apache | enable/disable certain packages
#   with-ruby, no-ruby     |
#   with-python, no-python |

include /usr/share/dpkg/architecture.mk

DEB_BUILD_MAINT_OPTIONS=future=+lfs

# Workaround an issue with PIC/PIE on certain architectures (c.f., #942798)
ifneq (,$(filter x32,$(DEB_HOST_ARCH)))
  DEB_BUILD_MAINT_OPTIONS+=hardening=+all,-pie
else
  DEB_BUILD_MAINT_OPTIONS+=hardening=+all
endif

include /usr/share/dpkg/default.mk

# Fully functional Java support is still a bit spotty on some Debian
# architectures.  DISABLE_JAVAHL_ARCHS overrides ENABLE_JAVAHL=yes.
# Note: the Build-Depends line in debian/control must be kept in sync
# with DISABLE_JAVAHL_ARCHS.

ENABLE_JAVAHL        = yes
ENABLE_APACHE        = yes
ENABLE_RUBY          = yes
ENABLE_PYTHON        = yes
ENABLE_KWALLET       = yes

DEB_BUILDDIR     = $(CURDIR)/BUILD
AUTH_LIB_DIRS    = $(DEB_BUILDDIR)/subversion/libsvn_auth_gnome_keyring/.libs:$(DEB_BUILDDIR)/subversion/libsvn_auth_kwallet/.libs
BASH_COMPL_DIR   = $(shell pkg-config --variable=completionsdir bash-completion)

export LANG = C
export HOME = $(DEB_BUILDDIR)/dummy_home

DISABLE_JAVAHL_ARCHS = hurd-i386 hurd-amd64 hppa sparc kfreebsd-i836 kfreebsd-amd64
ifneq (,$(filter $(DEB_HOST_ARCH), $(DISABLE_JAVAHL_ARCHS)))
  ENABLE_JAVAHL =
endif

ifeq (,$(filter libsvn-java,$(shell dh_listpackages)))
  ENABLE_JAVAHL =
endif

DISABLE_RUBY_ARCHS = ia64 kfreebsd-i386 kfreebsd-amd64
ifneq (,$(filter $(DEB_HOST_ARCH), $(DISABLE_RUBY_ARCHS)))
  ENABLE_RUBY =
endif

ifeq (,$(filter ruby-svn,$(shell dh_listpackages)))
  ENABLE_RUBY =
endif

DISABLE_KWALLET_ARCHS = alpha kfreebsd-i386 kfreebsd-amd64 m68k sparc64
ifneq (,$(filter $(DEB_HOST_ARCH), $(DISABLE_KWALLET_ARCHS)))
  ENABLE_KWALLET =
endif

ifneq (,$(filter pkg.subversion.nokde,$(DEB_BUILD_PROFILES)))
  ENABLE_KWALLET =
endif

# ENABLE_FOO -> DEB_OPT_WITH_FOO=1
# DEB_BUILD_OPTIONS='foo bar' -> DEB_OPT_FOO=1, DEB_OPT_BAR=1
# DEB_BUILD_OPTIONS='no-foo' -> DEB_OPT_WITH_FOO=""
$(foreach o, JAVAHL APACHE RUBY PYTHON KWALLET, $(if $(filter y yes 1,$(ENABLE_$o)), \
    $(eval DEB_OPT_WITH_$o := 1),$(eval DEB_OPT_WITH_$o :=)))
d_b_o:=$(shell echo "$$DEB_BUILD_OPTIONS" | tr 'a-z-,' 'A-Z_ ')
$(foreach o, $(d_b_o), \
  $(if $(findstring =,$o), $(eval DEB_OPT_$o), $(eval DEB_OPT_$o := 1)))
$(foreach o, $(filter NO_%,$(d_b_o)), $(eval DEB_OPT_$(subst NO_,WITH_,$o) :=))
$(if $(DEB_OPT_PARALLEL),$(eval MAKEFLAGS += -j$(DEB_OPT_PARALLEL)))

MAKE_B = $(MAKE) -C $(DEB_BUILDDIR)
ifndef DEB_OPT_TERSE
  MAKE_B += LTFLAGS="--tag=CC --verbose" LTCXXFLAGS="--tag=CXX --verbose"
endif

export CFLAGS CXXFLAGS CPPFLAGS LDFLAGS

# How to fix "#!/usr/bin/env " lines:  $(call fix_shebangs_in, /your/dir)
fix_shebangs_in = \
	find $1 -type f | xargs -r egrep -m1 -c '^\#! ?/' | sed -n 's/:1//p' |\
	xargs -r sed -i -e 's:^\#! */usr/bin/env perl.*:\#!/usr/bin/perl -w:' \
			-e 's:^\#! */usr/bin/env pyth.*:\#!/usr/bin/python3:' \
			-e 's:^\#! */usr/bin/env ruby.*:\#!/usr/bin/$(RUBY):'

PERL_DIR = $(DEB_BUILDDIR)/subversion/bindings/swig/perl/native
PY_DIR = $(DEB_BUILDDIR)/subversion/bindings/swig/python
PYVERSIONS = $(shell py3versions -vs)
PYDEFAULT =$(shell py3versions -vd)

allpy = \
	set -e; for v in $(PYVERSIONS); do \
		$(RM) $(PY_DIR); \
		ln -sfT python$$v $(PY_DIR); \
		pyinc=$$(python$$v-config --includes); \
		pylib=$$(python$$v -c 'import sysconfig; print(sysconfig.get_path("platlib", "deb_system"))'); \
		$1; \
		ln -sfT python$(PYDEFAULT) $(PY_DIR); \
	done

libdir = /usr/lib/$(DEB_HOST_MULTIARCH)
# ~max(min required sqlite, stable's sqlite)
MIN_SQLITE_VER = 3.8.7

confflags = \
		--with-apr=/usr \
		--with-apr-util=/usr \
		--with-serf=/usr \
		--enable-sqlite-compatibility-version=$(MIN_SQLITE_VER) \
		--with-berkeley-db=:::db \
		--with-sasl=/usr \
		--with-editor=/usr/bin/editor \
		--with-swig=/usr/bin/swig \
		--with-lz4 \
		--with-utf8proc \
		--enable-plaintext-password-storage \
		--with-gnome-keyring

ifdef DEB_OPT_DEBUG
  confflags+= --enable-debug
endif

ifdef DEB_OPT_WITH_KWALLET
  confflags += --with-kwallet=/usr/include:$(libdir)
endif

export DH_OPTIONS
ifdef DEB_OPT_WITH_JAVAHL
  # jikes 1.22 cannot compile javahl.
  confflags += --enable-javahl --without-jikes \
               --with-jdk=/usr/lib/jvm/default-java \
               --with-junit=/usr/share/java/junit4.jar
else
  DH_OPTIONS += -Nlibsvn-java
  confflags += --disable-javahl
endif

ifdef DEB_OPT_WITH_APACHE
  confflags += --with-apxs=/usr/bin/apxs2 --disable-mod-activation --with-apache-libexecdir=/usr/lib/apache2/modules
else
  confflags += --without-apxs
  DH_OPTIONS += -Nlibapache2-mod-svn
endif

ifdef DEB_OPT_WITH_RUBY
  RUBY = ruby
  RUBY_ARCH_DIR = $(shell $(RUBY) -rrbconfig -e "print RbConfig::CONFIG['vendorarchdir']")
  rb_defs = SWIG_RB_SITE_LIB_DIR=$(shell $(RUBY) -rrbconfig -e "print RbConfig::CONFIG['vendordir']")
  rb_defs += SWIG_RB_SITE_ARCH_DIR=$(RUBY_ARCH_DIR)
  confflags += --with-ruby-sitedir=/usr/lib/ruby
else
  DH_OPTIONS += -Nruby-svn
  RUBY = fooby
endif

ifdef DEB_OPT_WITH_PYTHON
  PYTHON = python3
else
  DH_OPTIONS += -Npython3-subversion
  PYTHON = foothon3
endif

# Set autoconf cross-compile mode correctly.
# Also disable testsuite if cross-compiling.
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)
  DEB_OPT_NOCHECK = 1
endif


# I'm not trying to be difficult: this check exists because building as
# root really _does_ fail.  The failure mode as of 1.4.0 is test 17
# from switch_tests.py.  Upstream response is "so don't build as root".
# (fakeroot does not fail, as it does not wrap the access(2) syscall.)
#
# We run this code from build-arch, since that's what actually fails as
# root, but also from autogen, since that will halt the build earlier.
define DONT_BE_ROOT
	@if [ $$(id -u) = 0 ] && [ -z "$(FAKEROOTKEY)" ]; then \
		echo >&2 "***"; \
		echo >&2 "*** Building as root is not supported ***"; \
		false; \
	fi
endef

%:
	dh $@ --with python3 --with apache2 --builddirectory=BUILD

execute_after_dh_update_autotools_config:
	./autogen.sh

override_dh_autoreconf:

override_dh_auto_configure:
	mkdir -p $(HOME)
	env PYTHON=/usr/bin/$(PYTHON) RUBY=/usr/bin/$(RUBY) dh_auto_configure --builddirectory=BUILD -- $(confflags)

	# Ensure we're able to regenerate the swig bindings, in case we need to
	# patch them.
	$(MAKE_B) mkdir-init
	$(MAKE_B) extraclean-bindings
ifdef DEB_OPT_WITH_PYTHON
	for v in $(PYVERSIONS); do \
		cp -la $(PY_DIR) $(PY_DIR)$$v; \
	done
	$(RM) -r $(PY_DIR)
	# $(PY_DIR) always needs to exist to avoid the upstream Makefiles from
	# trying to re-create it
	ln -sfT python$(PYDEFAULT) $(PY_DIR)
endif

check_defs = CLEANUP=1 LC_ALL=C
check_swig = $(if $(DEB_OPT_WITH_PYTHON),check-swig-py) check-swig-pl $(if $(DEB_OPT_WITH_RUBY),check-swig-rb)
check_all = $(check_swig) $(if $(DEB_OPT_WITH_JAVAHL),check-javahl) check
check-help:
	@echo "$(MAKE) $(check_all)"

override_dh_auto_test-indep:

override_dh_auto_test-arch:
ifndef DEB_OPT_NOCHECK
	$(MAKE) -f debian/rules $(check_all)
endif

check:
	# 'cat tests.log' is for obtaining diagnostics from buildd logs.
	@if ! $(MAKE) -C $(DEB_BUILDDIR) $@ $(check_defs) PARALLEL=$(DEB_OPT_PARALLEL); then \
	  echo "###################################################"; \
	  echo "Testsuite failed, 'tests.log' follows:"; echo; \
	  cat $(DEB_BUILDDIR)/tests.log; \
	  exit 1; \
	fi
	@if ! $(MAKE) -C $(DEB_BUILDDIR) davautocheck $(check_defs) PARALLEL=$(DEB_OPT_PARALLEL) APACHE_MPM=event; then \
	  echo "###################################################"; \
	  echo "mod_dav testsuite failed, 'tests.log' follows:"; echo; \
	  cat $(DEB_BUILDDIR)/tests.log; \
	  exit 1; \
	fi

check-swig-rb check-javahl:
	$(MAKE_B) $@ $(check_defs) PARALLEL=$(DEB_OPT_PARALLEL)

check-swig-pl:
	$(MAKE_B) $@ MAN3EXT=3perl $(check_defs)
	$(MAKE)  -C $(PERL_DIR) test MAN3EXT=3perl LC_ALL=C

check-swig-py:
	$(call allpy, \
	  $(MAKE_B) $@ SWIG_PY_PYTHON=python$$v PYTHON=python$$v PYVER=$$v $(check_defs))

override_dh_auto_build-arch:
	$(DONT_BE_ROOT)
	# note: autogen-swig does not support -jN
ifdef DEB_OPT_WITH_PYTHON
	$(call allpy, $(MAKE_B) -j1 autogen-swig-py)
endif
	$(MAKE_B) -j1 autogen-swig-pl
ifdef DEB_OPT_WITH_RUBY
	$(MAKE_B) -j1 autogen-swig-rb
endif
	$(MAKE_B) all tools
	# Run svn once, to make sure it populates $(HOME)/.subversion/*
	env LD_LIBRARY_PATH="$(AUTH_LIB_DIRS):$(LD_LIBRARY_PATH)" $(DEB_BUILDDIR)/subversion/svn/svn --version > /dev/null
ifdef DEB_OPT_WITH_PYTHON
	$(call allpy, \
	  $(MAKE_B) swig-py SWIG_PY_PYTHON=python$$v PYTHON=python$$v PYVER=$$v \
	            PYTHON_INCLUDES="$$pyinc" \
	            swig_pydir=$$pylib/libsvn swig_pydir_extra=$$pylib/svn)
endif
	# note: swig-pl seems to have trouble with -jN
	$(MAKE_B) -j1 swig-pl MAN3EXT=3perl
	$(MAKE) -C $(PERL_DIR) all \
		MAN3EXT=3perl OPTIMIZE="-g -Wall $(CFLAGS)"
ifdef DEB_OPT_WITH_RUBY
	$(MAKE_B) swig-rb $(rb_defs)
endif
ifdef DEB_OPT_WITH_JAVAHL
	$(MAKE_B) -j1 javahl
endif

override_dh_auto_build-indep:
	mkdir -p $(DEB_BUILDDIR)/doc/doxygen
	dh_auto_build --builddirectory=BUILD -- doc-api locale-gnu-pot

execute_before_dh_auto_clean:
	! [ -f $(DEB_BUILDDIR)/Makefile ] || $(MAKE) -C $(DEB_BUILDDIR) extraclean

execute_after_dh_auto_clean:
	find -name \*.pyc -exec $(RM) {} +

override_dh_installchangelogs:
	dh_installchangelogs CHANGES

override_dh_installdocs-indep override_dh_installdocs-arch:
	dh_installdocs NOTICE

override_dh_auto_install-indep:

PRIVATE_LIBS = auth_gnome_keyring auth_kwallet fs_base fs_fs fs_util fs_x ra_local ra_serf swig_perl $(foreach v, $(PYVERSIONS), swig_py$(v)) swig_ruby
override_dh_auto_install-arch:
	$(MAKE_B) -j1 local-install install-tools \
		DESTDIR=$(CURDIR)/debian/tmp toolsdir=/usr/bin pkgconfig_dir=$(libdir)/pkgconfig

ifdef DEB_OPT_WITH_PYTHON
	$(call allpy, \
	  set -e; \
	  $(MAKE_B) install-swig-py DESTDIR=$(CURDIR)/debian/tmp \
	            SWIG_PY_PYTHON=python$$v PYTHON=python$$v PYVER=$$v \
	            swig_pydir=$$pylib/libsvn swig_pydir_extra=$$pylib/svn; \
	  for ext in debian/tmp/usr/lib/python3/dist-packages/libsvn/*.so; do \
	    case $$ext in (*.cpython-*.so) continue; esac; \
	    mv $$ext $$(echo $$ext | sed "s/\.so$$/$$(python$$v-config --extension-suffix)/"); \
	  done)
	$(RM) debian/tmp/usr/lib/python*/*-packages/libsvn/*.la
	$(RM) debian/tmp/usr/lib/python*/*-packages/libsvn/*.a
endif

ifdef DEB_OPT_WITH_JAVAHL
	$(MAKE_B) install-javahl install-javahl-java \
		DESTDIR=$(CURDIR)/debian/tmp \
		javahl_javadir=/usr/share/java \
		javahl_javahdir=/usr/include/svn-javahl
endif

	$(MAKE_B) install-swig-pl-lib \
		DESTDIR=$(CURDIR)/debian/tmp
	$(MAKE) -C $(PERL_DIR) install \
		MAN3EXT=3perl DESTDIR=$(CURDIR)/debian/tmp INSTALLDIRS=vendor

ifdef DEB_OPT_WITH_RUBY
	$(MAKE_B) install-swig-rb $(rb_defs) \
		DESTDIR=$(CURDIR)/debian/tmp
endif

	rm -f $(foreach lib, $(PRIVATE_LIBS), debian/tmp/$(libdir)/libsvn_$(lib)-1.so)
	rm -f debian/tmp/usr/bin/diff*

	# There are some non-ELF files in /usr/bin, so ignore errors
	chrpath --keepgoing --delete "$(CURDIR)/debian/tmp/usr/bin/"* || true
	find "$(CURDIR)/debian/tmp$(libdir)" -type f -name '*.so' -exec chmod u+w '{}' + -exec chrpath --delete '{}' +

override_dh_install-arch:
	dh_install -Nruby-svn -X .in -X mailer/tests -X dontdothat -X .a -X .la

ifdef DEB_OPT_WITH_RUBY
	dh_install --autodest -pruby-svn -X .la -X .a debian/tmp$(RUBY_ARCH_DIR)
endif

	# Install files for 'subversion-tools' package.
	install $(DEB_BUILDDIR)/tools/backup/hot-backup.py \
		debian/subversion-tools/usr/bin/svn-hot-backup
	install -t debian/subversion-tools/usr/share/subversion/hook-scripts \
		$(DEB_BUILDDIR)/tools/hook-scripts/commit-access-control.pl

	# Fix some scripts not to use #!/usr/bin/env.
	$(call fix_shebangs_in, debian/*/usr/bin \
		debian/subversion-tools/usr/share/subversion/hook-scripts)
	cd debian/subversion-tools/usr/share/subversion/hook-scripts; \
		chmod 0755 commit-email.pl commit-access-control.pl \
			   mailer/mailer.py verify-po.py svnperms.py;

	# Remove suffixes from binaries in /usr/bin
	rename 's/\.(sh|pl|rb|py)$$//' debian/*/usr/bin/*

	pod2man -c 'User Commands' -r "" debian/contrib/svn-clean \
		$(DEB_BUILDDIR)/svn-clean.1

ifdef DEB_OPT_WITH_JAVAHL
	mkdir -p debian/libsvn-java/$(libdir)
	mv debian/libsvn-java/usr/lib/jni debian/libsvn-java/$(libdir)/
	$(RM) debian/libsvn-dev/$(libdir)/libsvnjavahl-1.so
endif

	install -d "debian/subversion/$(BASH_COMPL_DIR)"
	install -m644 tools/client-side/bash_completion \
		"debian/subversion/$(BASH_COMPL_DIR)/svn"
	cd "debian/subversion/$(BASH_COMPL_DIR)" \
	  && ln -s svn svnadmin \
	  && ln -s svn svndumpfilter \
	  && ln -s svn svnlook \
	  && ln -s svn svnversion

ifdef DEB_OPT_WITH_APACHE
	install subversion/mod_authz_svn/INSTALL \
		debian/libapache2-mod-svn/usr/share/doc/libapache2-mod-svn/INSTALL.authz
endif

override_dh_makeshlibs-arch:
	# dh_makeshlibs (1) creates shlibs/symbols files and (2) generates
	# calls to 'ldconfig' in postinst/postrm.  We want (1) only for
	# libsvn1, but (2) for the swig packages too.
	dh_makeshlibs -a -Xjava -X_auth_ -X_ra_serf -X_ra_local -X_fs_
	$(RM) debian/libsvn-*/DEBIAN/shlibs debian/python3-subversion/DEBIAN/shlibs
	$(RM) debian/libsvn-*/DEBIAN/symbols debian/python3-subversion/DEBIAN/symbols

override_dh_shlibdeps-arch:
	dh_shlibdeps -a -X_auth_
	sed -i 's:libsvn-private\(, *\)\?::' debian/*.substvars

override_dh_gencontrol-arch:
ifeq ($(DEB_VENDOR),Ubuntu)
	dh_gencontrol -a -- -V"subversion-tools:Suggests=svn2cl"
else
	dh_gencontrol -a -- -V"subversion-tools:Recommends=svn2cl"
endif

.NOTPARALLEL:
.PHONY: check-help $(check_all)