#!/usr/bin/make -f

include /usr/share/dpkg/architecture.mk
include /usr/share/dpkg/pkg-info.mk

## Security Hardening
export DEB_BUILD_MAINT_OPTIONS = hardening=+all optimize=-lto
export DEB_CFLAGS_MAINT_APPEND = -fPIC
export DEB_CXXFLAGS_MAINT_APPEND = -fPIC
export DEB_LDFLAGS_MAINT_APPEND = -fPIC
export DEB_CPPFLAGS_MAINT_APPEND = -DNDEBUG -UDEBUG \
  -DBORINGSSL_ANDROID_SYSTEM \
  -DBORINGSSL_IMPLEMENTATION \
  -DBORINGSSL_SHARED_LIBRARY \
  -DOPENSSL_SMALL \
  -fmessage-length=0 \
  -fno-exceptions \
  -fno-strict-aliasing \
  -no-canonical-prefixes \

ifneq (, $(shell which clang-13))
  export CC = clang-13
  export CXX = clang++-13
  export DEB_CFLAGS_MAINT_APPEND += -gdwarf-4
  export DEB_CXXFLAGS_MAINT_APPEND += -gdwarf-4
endif
ifneq (, $(shell which lld-13))
  export DEB_LDFLAGS_MAINT_APPEND += -fuse-ld=lld-13 -Wl,--build-id=sha1
endif

%:
	dh $@

# Since this depends on golang-go, not gccgo, so let's update manually
# Depends: golang-go
update-sources-mk:
	dpkg-source --before-build .
	python3 src/util/generate_build_files.py eureka
	cp eureka.mk debian/sources.mk
get-orig-source:
	gbp import-orig --uscan --no-interactive --postimport="\
		dch -b -v\$$GBP_DEBIAN_VERSION \"New upstream release \$$GBP_UPSTREAM_VERSION\"; \
		git add debian/changelog; \
		git commit -m\"dch: Note new upstream version \$$GBP_UPSTREAM_VERSION\""
update: get-orig-source update-sources-mk
	git diff --quiet debian/sources.mk || \
		(dch -a "debian/sources.mk: Update by script."; \
		git add debian/sources.mk debian/changelog; \
		git commit --amend -m "d/sources.mk: Update by script")
	git clean -fdx; git reset --hard

lib%.so: debian/lib%.mk
	dh_auto_build --buildsystem=makefile -- --file=$<

compiler_test: debian/compiler_test.mk
	dh_auto_build --buildsystem=makefile -- --file=$<
	LD_LIBRARY_PATH=debian/out debian/out/$@

%_test: debian/%_test.mk libtest_support.so libcrypto.so libssl.so
	dh_auto_build --buildsystem=makefile -- --file=$<

ifneq ($(DEB_HOST_ARCH), hurd-i386)
override_dh_auto_build-arch: compiler_test tool_test
else
# TODO: tool_test build fails on hurd-i386 currently
override_dh_auto_build-arch: compiler_test
endif
	dh_auto_build

ifeq (,$(findstring nocheck, $(DEB_BUILD_OPTIONS)))
override_dh_auto_test-arch: crypto_test ssl_test
ifneq ($(DEB_HOST_ARCH), hurd-i386)
	LD_LIBRARY_PATH=debian/out debian/out/bssl-tool genrsa
endif
	LD_LIBRARY_PATH=debian/out debian/out/crypto_test
	LD_LIBRARY_PATH=debian/out debian/out/ssl_test
endif

override_dh_dwz:
	dh_dwz || true
