#!/usr/bin/make -f

DEB_BUILD_MAINT_OPTIONS = hardening=+all
include /usr/share/dpkg/buildflags.mk
include /usr/share/dpkg/architecture.mk

# _FORTIFY_SOURCE=2 doesn't work with Neovim due to some old style variable
# length arrays
CPPFLAGS := $(subst _FORTIFY_SOURCE=2,_FORTIFY_SOURCE=1,$(CPPFLAGS))
# cmake doesn't honor CPPFLAGS
CFLAGS += $(CPPFLAGS) -DDISABLE_LOG -fno-strict-aliasing
CXXFLAGS += $(CPPFLAGS)

export CFLAGS CXXFLAGS LDFLAGS

BITOP_DEPENDS = lua-bitop
PREFER_LUA = ON
FUNCTIONALTEST =
UNITTEST =
COMPILE_LUA = ON

ifneq (,$(findstring ok installed,$(shell dpkg-query -W -f '$${Status}' lua-nvim 2>&1)))
  FUNCTIONALTEST = functionaltest
endif

ifneq (,$(findstring ok installed,$(shell dpkg-query -W -f '$${Status}' luajit 2>&1)))
  BITOP_DEPENDS =
  PREFER_LUA = OFF
  UNITTEST = unittest
  COMPILE_LUA = OFF
endif

# Default test timeout upstream is 20 minutes.  Extend this to 45 minutes
TIMEOUT=TEST_TIMEOUT=2700

FUNCTEST_FILTER_OUT=
ifneq (,$(filter armhf,$(DEB_HOST_ARCH)))
  FUNCTEST_FILTER_OUT='memory usage releases memory when closing windows when folds exist'
endif

export USERNAME = team+vim
export HOSTNAME = tracker.debian.org

USER = $(shell id -un)
ID = $(shell id -u)
GID = $(shell id -g)

ifeq (,$(filter terse,$(DEB_BUILD_OPTIONS)))
  BUILD = ninja -v -C build
else
  BUILD = ninja -C build
endif

BUILD_TYPE=Release
ifneq (,$(filter nooopt,$(DEB_BUILD_OPTIONS)))
  BUILD_TYPE=Debug
endif

%:
	dh $@ --buildsystem=cmake --builddirectory=build

override_dh_auto_configure:
	dh_auto_configure -- -G Ninja -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) -DBUSTED_OUTPUT_TYPE=nvim -DPREFER_LUA=$(PREFER_LUA) -DLIBLUV_LIBRARY:FILEPATH=/usr/lib/$(DEB_HOST_MULTIARCH)/lua/5.1/luv.so -DLIBLUV_INCLUDE_DIR:PATH=/usr/include/lua5.1 -DCOMPILE_LUA=$(COMPILE_LUA)

override_dh_auto_build:
	$(BUILD)

override_dh_auto_install:
	env DESTDIR=$(CURDIR)/debian/tmp $(BUILD) install

override_dh_auto_clean:
	$(MAKE) clean
	dh_auto_clean

override_dh_gencontrol:
	dh_gencontrol -- -Vneovim:Depends=$(BITOP_DEPENDS)

debian/passwd:
	printf -- "$(USER):x:$(ID):$(GID):nvim test:$(CURDIR)/debian/fakehome:/bin/false\n" > debian/passwd
	printf -- "users:x:$(GID):\n" > debian/group

debian/fakehome:
	mkdir -p debian/fakehome

debian/fakehome/locale-stamp:
	mkdir -p debian/fakehome/locale
	localedef -f UTF-8 -i en_US debian/fakehome/locale/en_US.UTF-8
	touch $@

override_dh_auto_test-indep:
	$(BUILD) $(UNITTEST)
