Skip to content

Instantly share code, notes, and snippets.

@takumin
Last active December 25, 2019 14:23
Show Gist options
  • Save takumin/39663c1f9fa22ebf0f3e8267482cf584 to your computer and use it in GitHub Desktop.
Save takumin/39663c1f9fa22ebf0f3e8267482cf584 to your computer and use it in GitHub Desktop.
[WIP] Cloud Hypervisor Network Boot Image
kernel.img
initrd.img
rootfs.squashfs
#!/bin/bash
# shellcheck disable=SC2086
: ${IMAGE_FILE:='/tmp/boot.img'}
# shellcheck disable=SC2086
: ${IMAGE_SIZE:='512M'}
# shellcheck disable=SC2086
: ${MOUNT_DIR:='/mnt'}
set -eux
# Unmount EFI System Partition
if grep -qs "\s${MOUNT_DIR}\s" "/proc/mounts"; then
umount "${MOUNT_DIR}"
fi
# Unmount Loopback Device
if losetup -lnO NAME,BACK-FILE | grep -qs "${IMAGE_FILE}"; then
losetup -d "$(losetup -nlO NAME,BACK-FILE | grep "${IMAGE_FILE}" | awk '{print $1}')"
fi
# Remove Old Disk Image
if [ -f "${IMAGE_FILE}" ]; then
rm "${IMAGE_FILE}"
fi
# Check Kernel Image File
if [ ! -f "kernel.img" ]; then
echo "Require kernel.img file"
exit 1
fi
# Check Initrd Image File
if [ ! -f "initrd.img" ]; then
echo "Require initrd.img file"
exit 1
fi
# Check Rootfs Image File
if [ ! -f "rootfs.squashfs" ]; then
echo "Require rootfs.squashfs file"
exit 1
fi
# Create Mount Directory
mkdir -p "${MOUNT_DIR}"
# Create RAW Disk Image
fallocate -l "${IMAGE_SIZE}" "${IMAGE_FILE}"
# Mount Loopback Device
LOOP_DEVICE="$(losetup --show -f -P "${IMAGE_FILE}")"
# Clear Partition Table
sgdisk -Z "${LOOP_DEVICE}"
# Create GPT Partition Table
sgdisk -o "${LOOP_DEVICE}"
# Create EFI Partition
sgdisk -n 1::-1 -c 1:EFI -t 1:ef00 "${LOOP_DEVICE}"
# Format EFI System Partition
mkfs.vfat -F 32 -n "ESP" "${LOOP_DEVICE}p1"
# Mount EFI System Partition
mount "${LOOP_DEVICE}p1" "${MOUNT_DIR}"
# Create Boot Loader Specification Directory
mkdir -p "${MOUNT_DIR}/loader/entries"
# Create Boot Loader Specification Loader File
cat > "${MOUNT_DIR}/loader/loader.conf" << __EOF__
default linux
timeout 0
editor no
auto-entries 0
auto-firmware 0
console-mode auto
__EOF__
# Create Boot Loader Specification Entry File
cat > "${MOUNT_DIR}/loader/entries/linux.conf" << __EOF__
title Linux
linux /boot/kernel.img
initrd /boot/initrd.img
options console=ttyS0 root=file:///boot/rootfs.squashfs overlayroot=tmpfs quiet ---
__EOF__
# Create Boot Image Directory
mkdir "${MOUNT_DIR}/boot"
# Copy Boot Image Files
cp "kernel.img" "${MOUNT_DIR}/boot/kernel.img"
cp "initrd.img" "${MOUNT_DIR}/boot/initrd.img"
cp "rootfs.squashfs" "${MOUNT_DIR}/boot/rootfs.squashfs"
# Unmount EFI System Partition
umount "${LOOP_DEVICE}p1"
# Unmount Loopback Device
losetup -d "${LOOP_DEVICE}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment