#!/bin/bash
#
# Generate a isolinux/bios and efi ISO boot image

set -e
PATH=/usr/bin:/bin:/usr/sbin:/sbin

dir="./debian/ipxe-qemu/usr/lib/ipxe/qemu/"
rc=0

declare -A roms
# these are the current power-of-2 buckets of roms generated by ipxe
# If any of these roms grows/shrinks out of its bucket a KVM
# live migration between two systems with those different sizes will fail.
# This check is intended to break builds on such a change to make it an opt-in
# change by a developer (to change the sizes below AFTER he has taken care that
# the qemu/libvirt on the migration paths will take care of it on migration).
# Due to ipxe (currently) not being part of Ubuntu Cloud Archive all UCA have
# the ipxe of the latest LTS. Which makes a certain qemu version (which defines
# the machine type) ambiguous which ipxe roms it has.
# Therefore such size breaking upgrades are only reasonably doable on LTS
# releases where qemu can assume all former types are of the former size
# and can handle all of these as one.
roms["efi-e1000.rom"]="524288"
roms["efi-eepro100.rom"]="524288"
roms["efi-ne2k_pci.rom"]="524288"
roms["efi-pcnet.rom"]="524288"
roms["efi-rtl8139.rom"]="524288"
roms["efi-virtio.rom"]="524288"
roms["efi-vmxnet3.rom"]="524288"
roms["pxe-e1000.rom"]="131072"
roms["pxe-eepro100.rom"]="131072"
roms["pxe-ne2k_isa.rom"]="131072"
roms["pxe-ne2k_pci.rom"]="131072"
roms["pxe-pcnet.rom"]="131072"
roms["pxe-rtl8139.rom"]="131072"
roms["pxe-virtio.rom"]="131072"
roms["pxe-vmxnet3.rom"]="131072"

echo "Generated roms:"
ls -laF "${dir}"

for rom in "${!roms[@]}"; do
    size=$(stat --printf="%s" "${dir}/${rom}")
    shiftsize="${size}"
    bucket=1
    while [ "${shiftsize}" -ne "1" ]; do
        shiftsize=$((shiftsize>>1))
        bucket=$((bucket<<1))
    done
    bucket=$((bucket<<1))
    # being smaller could be ok, but check -eq to warn/break on unexpected size loss as well
    if [ "${bucket}" -eq "${roms[$rom]}" ]; then
        echo "OK: ${rom} is ${size} bytes and thereby in bucket ${bucket} which matches ${roms[$rom]}"
    else
        echo "ERROR: ${rom} is ${size} bytes and thereby in bucket ${bucket} which does not match ${roms[$rom]}"
        rc=1
    fi
done

exit ${rc}
