#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS=hardening=+all
include /usr/share/dpkg/default.mk
export CFLAGS  += $(shell getconf LFS_CFLAGS)
export LDFLAGS += $(shell getconf LFS_LDFLAGS)
export prefix = $(CURDIR)/debian/ucspi-unix/usr
export mandir = share/man


# Package is built twice, with glibc and diet libc, but only $(FLAVOR)
# version is installed. This way following is achieved:
#
#  * diet version is protected from bitrot
#  * switching to diet version for downstream/local rebuild is as
#    smooth, as possible.
FLAVOR = glibc

HAVE_DIETLIBC=no
ifeq ($(shell dpkg -s dietlibc-dev | grep -o installed), installed)
  HAVE_DIETLIBC=yes
  BUILT_USING := $(shell dpkg-query -f'$${source:Package} (= $${source:Version})' -W dietlibc-dev)
  DIET_LIBDIR := $(shell diet -L gcc)
endif
ifeq ($(shell dpkg-vendor --derives-from Ubuntu && echo yes),yes)
  HAVE_DIETLIBC=no
endif


%:
	dh $@ --with buildinfo

override_dh_auto_configure:
	mkdir -p diet glibc
	find -maxdepth 1 -type f -printf '../%f\0' | xargs -0 ln -sft diet/
	find -maxdepth 1 -type f -printf '../%f\0' | xargs -0 ln -sft glibc/
	rm diet/conf-* glibc/conf-*
	echo '$(CC) $(CFLAGS) $(CPPFLAGS)' > glibc/conf-cc
	echo '$(CC) $(LDFLAGS)' > glibc/conf-ld
	echo 'diet gcc $(CFLAGS) $(CPPFLAGS)' > diet/conf-cc
	echo 'diet gcc $(LDFLAGS)' > diet/conf-ld

override_dh_auto_build:
ifeq (${HAVE_DIETLIBC},yes)
	$(MAKE) -C diet
endif
	$(MAKE) -C glibc

override_dh_auto_test:
ifeq (${HAVE_DIETLIBC},yes)
	env PYTHONPATH='$(CURDIR)/debian/tests/python' python3 -B -u -m ucspi_unix_test -d '$(CURDIR)/diet' -p unix
endif
	env PYTHONPATH='$(CURDIR)/debian/tests/python' python3 -B -u -m ucspi_unix_test -d '$(CURDIR)/glibc' -p unix

override_dh_auto_install:
	$(MAKE) -C $(FLAVOR) install

override_dh_auto_clean:
	rm -fr glibc/ diet/
