#!/bin/sh

# /etc/kernel/postinst.d/
# create single UEFI PE binary that embed everything needed to boot a system
# apt install systemd-ukify systemd-boot-efi

set -e

TARGET=/boot/efi/EFI/linux

VER=$1
[ "$VER" ] || VER=$(uname -r)
KVER=$2
[ "$KVER" ] || KVER="/boot/vmlinuz-$VER"
mkdir -pv "$TARGET"
DEV=$(awk '/\/boot\/efi/{print $1}' /proc/mounts)
#ENTRY="initrd=EFI\linux\initrd.img $(sed 's/BOOT_IMAGE=\S*\s*//' /proc/cmdline)"
#ENTRY2="$(sed 's/initrd=\S*\s*//' /proc/cmdline)"
ENTRY2="$(sed 's/BOOT_IMAGE=\S*\s*//' /proc/cmdline)"

/usr/lib/systemd/ukify build \
    --linux="$KVER" \
    --initrd="/boot/initrd.img-$VER" \
    --cmdline="$ENTRY2" \
    --output="$TARGET/linux.efi"

# Add this line if you want to sign the image for secure boot
#sbsign --key /path/to/db.key --cert /path/to/db.crt --output /boot/efi/EFI/Linux/debian.efi /boot/efi/EFI/Linux/debian.efi
for e in $(efibootmgr|awk -F'[ *]' '$2=/linux/{print $1}'); do efibootmgr -B -b ${e#Boot}; done
efibootmgr -c -d $(echo $DEV|sed 's/[0-9]\+$//') -p $(echo $DEV|sed 's/.*\([0-9]\+$\)/\1/') -l "\EFI\linux\linux.efi" -L "linux" -u "$ENTRY2"
