#!/usr/bin/make -f
SHELL := bash -e

include /usr/share/dpkg/default.mk

# grub is special, and the suffixes don't univocally match:
# for amd64 it's the GNU prefix, but for arm64 it's the arch
ifneq (,$(filter $(DEB_HOST_ARCH), arm64))
    GRUB_ARCH := $(DEB_HOST_ARCH)
else
    GRUB_ARCH := $(DEB_HOST_GNU_CPU)
endif

# When forking to a new signed package, it should be enough to change
# the following variables:
# - where to look for unsigned EFI binaries, and where to install them
# - unsigned package name
UNSIGNED_EFI_INSTALL_DIR := /usr/lib/grub/$(GRUB_ARCH)-efi/monolithic/
SIGNED_EFI_INSTALL_DIR := /usr/lib/grub/$(GRUB_ARCH)-efi-signed/
UNSIGNED_PACKAGE_NAME := grub-efi-$(DEB_HOST_ARCH)-bin
PACKAGE_NAME := grub-efi-$(DEB_HOST_ARCH)-signed
PACKAGE_DIR := debian/$(PACKAGE_NAME)
INSTALL_DIR := $(PACKAGE_DIR)/$(SIGNED_EFI_INSTALL_DIR)
PACKAGE_VERSION := $(shell dpkg-query --showformat='$${Version}' --show $(UNSIGNED_PACKAGE_NAME))

%:
	dh $@ --with signobs

# Build with the original's version, changelog and copyright, as it makes
# more sense to have it match the unsigned binary

# Generate a strict dependency - the unsigned and signed packages must match
override_dh_gencontrol:
	dh_gencontrol -p $(PACKAGE_NAME) -- -v$(PACKAGE_VERSION) \
		-V'sign:Depends=$(UNSIGNED_PACKAGE_NAME) (= $(PACKAGE_VERSION))'

override_dh_installchangelogs:
	dh_installchangelogs
	gunzip -c /usr/share/doc/$(UNSIGNED_PACKAGE_NAME)/changelog.Debian.gz > \
		$(PACKAGE_DIR)/usr/share/doc/$(PACKAGE_NAME)/changelog

override_dh_installdocs:
	dh_installdocs
	cp /usr/share/doc/$(UNSIGNED_PACKAGE_NAME)/copyright \
		$(PACKAGE_DIR)/usr/share/doc/$(PACKAGE_NAME)/

override_dh_auto_install:
	install -m 0755 -d $(INSTALL_DIR)
	install -m 0644 -t $(INSTALL_DIR) $(UNSIGNED_EFI_INSTALL_DIR)/*.efi
