#!/usr/bin/make -f

export DH_VERBOSE = 1

include /usr/share/dpkg/pkg-info.mk
include /usr/share/dpkg/architecture.mk
include /usr/share/dpkg/buildflags.mk
include /usr/share/rustc/architecture.mk
export CFLAGS CXXFLAGS CPPFLAGS LDFLAGS
export DEB_HOST_RUST_TYPE DEB_HOST_GNU_TYPE

export CARGO=/usr/share/cargo/bin/cargo
export CARGO_HOME=$(shell pwd)/debian/cargo_home
export CARGO_VENDOR_DIR = rust-vendor
export DEB_CARGO_CRATE=$(DEB_SOURCE)_$(DEB_VERSION_UPSTREAM)

export DEB_BUILD_MAINT_OPTIONS=hardening=+bindnow

export PYBUILD_NAME=cryptography
export PYBUILD_TEST_PYTEST=1
# needs newer librust-openssl-dev (#1081226)
export PYBUILD_TEST_ARGS={dir}/tests/ -k 'not (TestDHPublicKeySerialization and test_public_bytes_match)'

VENDOR_TARBALL = ../$(DEB_SOURCE)_$(DEB_VERSION_UPSTREAM).orig-$(CARGO_VENDOR_DIR).tar.xz
VENDOR_OPENSSL_SYS := $(CARGO_VENDOR_DIR)/openssl-sys

%:
	dh $@ --buildsystem=pybuild


override_dh_auto_clean:
	if [ -f src/rust/Cargo.lock.orig ] ; then mv src/rust/Cargo.lock.orig src/rust/Cargo.lock ; fi
	dh_auto_clean
	rm -rf src/rust/target
	rm -rf debian/cargo_registry

# You may have to `dpkg-source --include-binaries -b .` to update
# `d/source/include-binaries` after updating vendored deps
vendor-tarball $(VENDOR_TARBALL):
	cargo vendor --manifest-path src/rust/Cargo.toml "$(CARGO_VENDOR_DIR)"
	# Remove everything vcpkg because it ships arm64 iOS .a files which trip
	# further steps and serve no purpose
	rm -r "$(CARGO_VENDOR_DIR)/vcpkg"
	jq -r '{ "files": {}, "package": .package }' < "$(VENDOR_OPENSSL_SYS)/.cargo-checksum.json" > "$(VENDOR_OPENSSL_SYS)/.cargo-checksum.json.tmp"
	mv "$(VENDOR_OPENSSL_SYS)/.cargo-checksum.json.tmp" "$(VENDOR_OPENSSL_SYS)/.cargo-checksum.json"
	sed -E -i -e '/^\[build-dependencies\.vcpkg\]$$/,+2 d' "$(VENDOR_OPENSSL_SYS)/Cargo.toml"
	sed -E -i -e '/ +try_vcpkg\(\);/ d' -e '/^fn try_vcpkg\(\) \{$$/,/^\}$$/ d' "$(VENDOR_OPENSSL_SYS)/build/find_normal.rs"
	sed -E -i -e '/^extern crate vcpkg;$$/ d' "$(VENDOR_OPENSSL_SYS)/build/main.rs"
	tar --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner --pax-option='exthdr.name=%d/PaxHeaders/%f,delete=atime,delete=ctime' -caf "$(VENDOR_TARBALL)" "$(CARGO_VENDOR_DIR)"
	rm -rf "$(CARGO_HOME)"

override_dh_sphinxdoc:
ifeq (,$(findstring nodoc, $(DEB_BUILD_OPTIONS)))
	PYTHONPATH=./src python3 -m sphinx -b html -N docs/ \
		   $(CURDIR)/debian/python-cryptography-doc/usr/share/doc/python-cryptography-doc/html
	dh_sphinxdoc
endif


override_dh_auto_configure:
	dh_auto_configure
	# This runs cargo prepare-debian and dh-cargo-vendored-sources when
	# CARGO_HOME is set, and other prepare-debian debian/cargo_registry
	# --link-from-system otherwise
	dh_auto_configure --buildsystem=cargo


override_dh_dwz:
	dh_dwz --no-dwz-multifile


override_dh_python3:
	# We patch it out of .dist-info to avoid pkg_resources complaining (#1026537)
	dh_python3 --depends=cffi

.PHONY: $(VENDOR_TARBALL)
