#!/usr/bin/make -f

include /usr/share/dpkg/architecture.mk
ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE))
  CC=$(DEB_HOST_GNU_TYPE)-gcc
else
  CC=gcc
endif

DEB_BUILD_MAINT_OPTIONS := hardening=+all
include /usr/share/dpkg/buildflags.mk
include /usr/share/dpkg/pkg-info.mk

LD_SO_PATH := $(shell readelf -e /usr/bin/dash | grep Requesting | sed 's/.$$//' | rev | cut -d" " -f1 | rev)

%:
	dh $@ --with autoreconf --exclude=.la

override_dh_auto_configure:
	dh_auto_configure -- \
		--without-rpm \
		--with-deb \
		--with-audit \
		--with-systemdsystemunitdir=/usr/lib/systemd/system

# fapolicyd/cli 的 Makefile.am 默认以 "-pie ... -static" 链接（静态 PIE）。
# OpenKylin(huanghe) 的 libdpkg.a 未按 -fPIC/-fPIE 编译（与 Ubuntu 不同），
# 链接 PIE 可执行文件时报：
#   relocation R_X86_64_32 against '.rodata' can not be used when making a PIE object
# 因此链接时改用 -no-pie（保留 -static 语义及 RELRO/BIND_NOW 加固）。
override_dh_auto_build:
	dh_auto_build -- \
		fapolicyd_LDFLAGS='-no-pie -Wl,-z,relro -Wl,-z,now -static' \
		fapolicyd_cli_LDFLAGS='-no-pie -Wl,-z,relro -Wl,-z,now -static'


# override_dh_installinit:
override_dh_installsystemd:
	dh_installsystemd --no-enable --no-start

override_dh_install:
	# generate rules for python
	sed -i "s/%python3_path%/`readlink -f /usr/bin/python3 | \
		sed 's/\//\\\\\//g'`/g" \
		$(CURDIR)/debian/fapolicyd/usr/share/fapolicyd/sample-rules/*.rules
	# Detect run time linker directly from dash
	sed -i "s|%ld_so_path%|`realpath $(LD_SO_PATH)`|g" \
		$(CURDIR)/debian/fapolicyd/usr/share/fapolicyd/sample-rules/*.rules

	dh_install

	rm -rf $(CURDIR)/debian/fapolicyd/usr/lib/*/*.la
	rm -rf $(CURDIR)/debian/fapolicyd/usr/lib/*/*.a
	rm -rf $(CURDIR)/debian/fapolicyd/etc/bash_completion.d
	find $(CURDIR)/debian/fapolicyd -type d -empty -delete
