Skip to content

Instantly share code, notes, and snippets.

Last active January 1, 2023 11:57
Show Gist options
  • Save kings-way/7525468212fea4df0d3e9bd420d13843 to your computer and use it in GitHub Desktop.
Save kings-way/7525468212fea4df0d3e9bd420d13843 to your computer and use it in GitHub Desktop.
# Author: kings_way
# Version: 20230101
# Build bootable image for BIOS and UEFI secure boot.
# Host OS: Ubuntu 20.04
set -e
# prepare dirs
rm -rf /tmp/work
mkdir -p /tmp/work/initrd
mkdir -p /tmp/work/rootfs/efi/{boot,ubuntu}
# install packages (assume the host has grub-efi already)
apt install shim-signed grub-efi-amd64-signed grub-pc-bin busybox-static
# build initramfs
cd /tmp/work/initrd
unmkinitramfs $INITRD_FILE .
for i in $(main/bin/busybox --list); do rm main/bin/$i; done
busybox --install main/bin
# hack init
sed -i '/load_modules/,$d' main/init
cat >> main/init << 'EOF'
clear && echo
[ -d "/sys/firmware/efi" ] && echo "[boot mode]: UEFI" || echo "[boot mode]: BIOS"
echo -n "[Secure Boot]: " && dmesg | grep -o "secureboot.*" | head -1 && echo
reboot -f
# delete useless drivers and tools
cd /tmp/work/initrd/main
rm -rf bin/plymouth usr/share/{fonts,plymouth} lib/x86_64-linux-gnu/libply*
rm -rf lib/i386-linux-gnu lib/x86_64-linux-gnu/plymouth lib/firmware/{netronome,amdgpu,radeon,mellanox,liquidio,cxgb4,nvidia,phanfw.bin}
cd /tmp/work/initrd/main/lib/modules/
for i in `ls`;do
cd /tmp/work/initrd/main/lib/modules/"$i"/kernel/drivers
rm -rf {../net,../sound,../fs,../../updates,net,gpu,regulator,thunderbolt,firewire,fpga,infiniband}
# build the initrd
cd /tmp/work/initrd/main
find . | cpio -o -Hnewc | gzip > /tmp/work/initrd/initrd.gz
# install shim, grub, kernel and initrd
cd /tmp/work/rootfs
cp -avH /usr/lib/shim/shimx64.efi.signed efi/boot/bootx64.efi
cp -avH /usr/lib/grub/x86_64-efi-signed/grubx64.efi.signed efi/boot/grubx64.efi
cp -avH $KERNEL_FILE efi/ubuntu/vmlinuz
cp -avH /tmp/work/initrd/initrd.gz efi/ubuntu/initrd
# setup grub.cfg
cat > efi/ubuntu/grub.cfg << 'EOF'
echo 'Loading kernel...'
linux /efi/ubuntu/vmlinuz ro quiet
echo 'Loading initramfs...'
initrd /efi/ubuntu/initrd
echo 'Booting...'
# build img
cd /tmp/work
IMG_SIZE=$(du -hs rootfs|awk '{print $1}')
fallocate -o 8M -l "$IMG_SIZE" boot.img
# UEFI boot img
#echo -ne 'g\n n\n\n\n\n t\n C12A7328-F81F-11D2-BA4B-00A0C93EC93B\n w\n' | fdisk boot.img
# BIOS/UEFI (MBR/GPT) hybrid boot img
echo -ne 'g\n n\n\n\n+1M\n t\n 21686148-6449-6E6F-744E-656564454649\n n\n\n\n\n t\n\n C12A7328-F81F-11D2-BA4B-00A0C93EC93B\n w\n' | fdisk boot.img
losetup -P loop7788 boot.img
mkfs.fat -F32 /dev/loop7788p2
mkdir loop
mount /dev/loop7788p2 /tmp/work/loop
# grub, i386-pc
grub-install --target=i386-pc --root-directory=/tmp/work/loop /dev/loop7788
cp -avH rootfs/efi/ubuntu/grub.cfg loop/boot/grub/
# grub, x86_64-efi
cp -avrH rootfs/* loop/ && sync && umount loop && losetup -d /dev/loop7788
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment