#! /bin/bash

base_initrd=dist/initrd
flavor=dhcp
dir=tmp/$flavor-initrd

dist=dist/$flavor
uki=$dist/bootx64.efi

linux_v=6.18.34

set -ex

mkdir -p tmp/dl $dist

linux=tmp/dl/linux-$linux_v
modules=tmp/dl/modules-$linux_v

[ -e $linux ]   || curl -o $linux   https://dkl.novit.io/dist/kernels/6.18.34
[ -e $modules ] || curl -o $modules https://dkl.novit.io/dist/layers/modules/6.18.34 # TODO .erofs

rm -fr $dir
mkdir $dir

cpio --quiet --extract --file $base_initrd --directory $dir

cp -rv $flavor/. $dir
cp $modules $dir/modules.fs

(cd $dir && find * |cpio --create -H newc -R 0:0) >$dir.cpio

if cpio -tF $dir.cpio 2>&1 |grep bytes.of.junk; then echo "bad cpio archive"; exit 1; fi

zstd -12 -T0 -vf $dir.cpio &&
mv $dir.cpio.zst $dist/initrd
cp $linux $dist/vmlinuz

ukify build --output $uki --os-release "Direktil DHCP" \
    --linux $linux --initrd $dist/initrd --cmdline "console=tty0 console=ttyS0,115200"

MB=$(( 2**20 ))
sz=$(( ( $(stat -c %s $uki) + MB ) / MB + 2 ))

efi=$dist/efi.img

if [ -e $efi ]; then rm $efi; fi

truncate -s ${sz}M $efi
sgdisk -n 1:2048:0 -t 1:ef00 -c 1:"EFI System" $efi

offset=$(( 2048 * 512 ))

export MTOOLSRC=$(mktemp)
trap "rm -f $MTOOLSRC" exit
echo "drive e: file=\"$efi\" offset=$offset" >$MTOOLSRC

args="-i $efi@@$offset"

mformat -F e:
mmd e:EFI e:EFI/BOOT
mcopy $uki e:EFI/BOOT/BOOTX64.EFI

