#!/usr/bin/make -f

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

# cmake doesn't honor CPPFLAGS
CFLAGS += $(CPPFLAGS) -DDISABLE_LOG
CXXFLAGS += $(CPPFLAGS)

export CFLAGS CXXFLAGS LDFLAGS

PREFER_LUA = ON
FUNCTIONALTEST =
UNITTEST =
ifneq (,$(findstring ok installed,$(shell dpkg-query -W -f '$${Status}' lua-nvim)))
  FUNCTIONALTEST = functionaltest
endif

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

export USERNAME = pkg-vim-maintainers
export HOSTNAME = lists.alioth.debian.org

USER = $(shell id -un)
ID = $(shell id -u)
GID = $(shell id -g)
BUILD = ninja -v -C build

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

override_dh_auto_configure:
	dh_auto_configure -- -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUSTED_OUTPUT_TYPE=nvim -DPREFER_LUA=$(PREFER_LUA)

override_dh_auto_build:
	$(BUILD)

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

override_dh_install:
	dh_install --fail-missing

override_dh_auto_clean:
	$(MAKE) clean
	dh_auto_clean

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

override_dh_auto_test-indep:

ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
override_dh_auto_test-arch: debian/passwd debian/fakehome
	env "HOME=$(CURDIR)/debian/fakehome" $(MAKE) -C src/nvim/testdir clean
	env "HOME=$(CURDIR)/debian/fakehome" TERM=xterm $(MAKE) -C src/nvim/testdir "NVIM_PRG=$(CURDIR)/build/bin/nvim"
ifneq (,$(UNITTEST)$(FUNCTIONALTEST))
	env TEST_SKIP_FRAGILE=1 "HOME=$(CURDIR)/debian/fakehome" LD_PRELOAD=libnss_wrapper.so "NSS_WRAPPER_PASSWD=$(CURDIR)/debian/passwd" "NSS_WRAPPER_GROUP=$(CURDIR)/debian/group" $(BUILD) $(UNITTEST) $(FUNCTIONALTEST)
endif
endif
