#!/bin/sh
# fireme: build a Firecracker ext4 rootfs from ./Dockerfile.
# Needs docker and e2fsprogs (mkfs.ext4); run from the build context.
set -eu
docker build -t time-api-e1bf:fireme .
cid=$(docker create time-api-e1bf:fireme)
rm -rf rootfs && mkdir rootfs
docker export "$cid" | tar -C rootfs -xf -
docker rm "$cid" >/dev/null
# PID 1 for the guest, as heyo adds it, unless the image brought its own.
if [ ! -e rootfs/init.sh ]; then
  cat > rootfs/init.sh <<'INIT'
#!/bin/sh
mount -t proc proc /proc; mount -t sysfs sysfs /sys; mount -t devtmpfs devtmpfs /dev
mkdir -p /dev/pts /run /tmp; mount -t devpts devpts /dev/pts; chmod 1777 /tmp
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
grep -q nameserver /etc/resolv.conf 2>/dev/null || echo "nameserver 8.8.8.8" > /etc/resolv.conf
grep -qw localhost /etc/hosts 2>/dev/null || echo "127.0.0.1 localhost" >> /etc/hosts
echo "HEYVM_READY"
while :; do [ -x /bin/sh ] && /bin/sh; sleep 1; done
INIT
  chmod +x rootfs/init.sh
fi
mb=$(du -sm rootfs | cut -f1)
size=$((mb * 12 / 10 + 64))
rm -f time-api-e1bf.ext4
truncate -s "${size}M" time-api-e1bf.ext4
mkfs.ext4 -q -F -d rootfs time-api-e1bf.ext4
echo "built time-api-e1bf.ext4 (${size} MB)"
echo "boot: firecracker rootfs=/dev/vda, boot_args=\"console=ttyS0 root=/dev/vda rw init=/init.sh\""
