#!/usr/bin/make -f
export LC_ALL = C
export DEB_BUILD_MAINT_OPTIONS = hardening=+all reproducible=+all
include /usr/share/dpkg/default.mk

# Upstream source code in src/version.c uses __DATE__ and __TIME__
# macros, making build unreproducible. Instead of maintaining patch to
# remove those macros (and refreshing it every upstream release), here
# we redefine to something stable. Note, that __DATE__ is redefined to
# format, different from one, prescribed by ISO C standard, since
# passing around value, containing spaces is huge pain.
#
# gcc will complain, it is okay.
RELEASE_DATE := $(shell date --date "@$(SOURCE_DATE_EPOCH)" +'%Y-%m-%d')
RELEASE_TIME := $(shell date --date "@$(SOURCE_DATE_EPOCH)" +'%H:%M:%S')
export CFLAGS += -D__DATE__='"$(RELEASE_DATE)"'
export CFLAGS += -D__TIME__='"$(RELEASE_TIME)"'

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 $@

override_dh_auto_configure:
ifeq ($(HAVE_DIETLIBC),yes)
	dh_auto_configure -B diet-build --  \
	    --libdir $(DIET_LIBDIR) \
	    --disable-shared \
	    --enable-static \
	    --enable-largefile \
	    --enable-memory-mapped-io=no \
	    CC='diet gcc' CPPFLAGS='-UHAVE_MMAP'
endif
	dh_auto_configure -B glibc-build -- --enable-libgdbm-compat --enable-largefile
	dh_auto_configure -B glibc-nolfs-build -- \
	    CFLAGS='-static -O2 -g' --program-suffix=-nolfs --disable-largefile

override_dh_auto_build:
ifeq ($(HAVE_DIETLIBC),yes)
	dh_auto_build -B diet-build
endif
	dh_auto_build -B glibc-build
	dh_auto_build -B glibc-nolfs-build

override_dh_auto_install:
ifeq ($(HAVE_DIETLIBC),yes)
	dh_auto_install -B diet-build
endif
	dh_auto_install -B glibc-nolfs-build
	dh_auto_install -B glibc-build

ifeq ($(HAVE_DIETLIBC),yes)
override_dh_gencontrol:
	dh_gencontrol -- -VBuilt-Using="$(BUILT_USING)" -Vlibgdbm-dietlibc:Provides=libgdbm-dietlibc-dev
endif

override_dh_install:
	dh_install
ifeq ($(HAVE_DIETLIBC),yes)
	dh_install -plibgdbm-dev /usr/lib/*/diet/*/libgdbm.a
endif
