#!/usr/bin/make -f

# export DH_VERBOSE=1

export DEB_BUILD_MAINT_OPTIONS = hardening=+all optimize=+lto
export DEB_LDFLAGS_MAINT_APPEND = -Wl,-z,noexecstack

# crossbuild
ifneq  ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
include /usr/share/dpkg/buildtools.mk
endif

%:
	dh $@

# In the debian/compiler directory contains gcc and clang wrappers.
# It adds Debian specifific options distributed in
# $CC, $CFLAGS, $CPPFLAGS and $LDFLAGS
export PATH := $(shell pwd)/debian/compiler:$(PATH)

# Detects the correct ABINAME from the DEB_BUILD_ARCH
# instead of run-time detection. Fixes FTBR.
ABINAME=$(DEB_BUILD_ARCH)
ifeq ($(ABINAME), x32)
ABINAME=amd64
endif

.PHONY: select_implementations
select_implementations:
	# disable all implementations
	ls -1d crypto_*/*/* \
	| while read d; \
	do \
	  chmod +t "$${d}"; \
	done
	# enable portable implementations
	chmod -t crypto_dh/x25519/wrapper
	chmod -t crypto_hash/sha512/ref
	chmod -t crypto_hashblocks/sha512/inplace
	chmod -t crypto_mGnP/ed25519/ref10
	chmod -t crypto_multiscalar/ed25519/ref10
	chmod -t crypto_nG/montgomery25519/usemerged
	chmod -t crypto_nG/merged25519/ref10
	chmod -t crypto_nP/montgomery25519/ref10
	chmod -t crypto_nPbatch/montgomery25519/ref
	chmod -t crypto_pow/inv25519/ref10
	chmod -t crypto_powbatch/inv25519/ref10
	chmod -t crypto_sign/ed25519/ref10
	chmod -t crypto_verify/32/ref
	# enable amd64 implementations
	chmod -t crypto_sign/ed25519/amd64
	chmod -t crypto_mGnP/ed25519/amd64-maa4
	chmod -t crypto_multiscalar/ed25519/amd64-maa4
	chmod -t crypto_nG/merged25519/amd64-maa4
	chmod -t crypto_nP/montgomery25519/amd64-maa4
	chmod -t crypto_pow/inv25519/amd64-maa4
	# enable amd64 avx2 implementations
	chmod -t crypto_hash/sha512/blocksplusavx
	chmod -t crypto_hashblocks/sha512/avx2
	chmod -t crypto_mGnP/ed25519/amd64-avx2-9l-mxaa
	chmod -t crypto_multiscalar/ed25519/amd64-avx2-9l-mxaa-p3
	chmod -t crypto_nG/merged25519/amd64-avx2-9l-mxaa
	chmod -t crypto_nP/montgomery25519/amd64-avx2-ns10l-mxaa
	chmod -t crypto_nPbatch/montgomery25519/amd64-avx2-4x1-10l-mxaa
	chmod -t crypto_pow/inv25519/amd64-safegcd
	# enable amd64 avx512 implementations
	chmod -t crypto_multiscalar/ed25519/amd64-avx512ifma-5l-maax-p3
	chmod -t crypto_nG/merged25519/amd64-avx512ifma-5l-maax
	chmod -t crypto_nP/montgomery25519/amd64-avx512ifma-ns5l-maax
	chmod -t crypto_nPbatch/montgomery25519/amd64-avx512ifma-8x1-maax

override_dh_auto_configure: select_implementations
	./configure --host=$(ABINAME) --prefix=/usr

override_dh_auto_clean:
	rm -rf ./build

# disable auto installation
override_dh_auto_install:
