#! /usr/bin/env bash

set -e

# Not included:
#  1. Downloading huge.s from Slackware64 kernels (into boot/)
#  2. Downloading kernel modules package from Slackware64 (into root/)
#  3. Running "depmod" within the chroot root/
#  4. Downloading a static Tclkit with TUAPI
#  5. Downloading a static AppFS

image_file="$(pwd)/appfs.img"
old_loop_dev="$(losetup --noheadings --output name --associated "${image_file}")" || old_loop_dev=''
extlinux_mbr_bin='/usr/lib/EXTLINUX/mbr.bin'

make init LDFLAGS=-static
cp init root/bin

rm -f boot/initrd
(
	cd root || exit 1
	find . ! -name '.' -print0 | sort --zero-terminated --dictionary-order | cpio -o -0 --owner 0:0 --dot -H newc
) | gzip -1c > boot/initrd

rm -f "${image_file}"
truncate --size 1024M "${image_file}"
sfdisk --no-tell-kernel --no-reread "${image_file}" <<<'label: dos
size=128M type=83 bootable
type=83'

if [ -d 'x-boot' ]; then
	sudo umount x-boot || :
fi
if [ -n "${old_loop_dev}" ]; then
	sudo losetup -d "${old_loop_dev}" || :
fi
sudo losetup --partscan --find "${image_file}"
loop_dev="$(losetup --noheadings --output name --associated "${image_file}")"
if [ -z "${loop_dev}" ]; then
	echo "No loop device found" >&2
	exit 1
fi
sudo chown "$(id -u):$(id -g)" "${loop_dev}" "${loop_dev}p1" "${loop_dev}p2"

mke2fs \
  -L 'BOOT' \
  -N 0 \
  -O ^64bit \
  -d boot \
  -m 5 \
  -r 1 \
  -t ext4 \
  "${loop_dev}p1"

mke2fs \
  -L 'DATA' \
  -N 0 \
  -O ^64bit \
  -m 5 \
  -r 1 \
  -t ext4 \
  "${loop_dev}p2"

mkdir x-boot || :
sudo mount "${loop_dev}p1" x-boot
sudo extlinux --install $(pwd)/x-boot
sudo umount x-boot
dd if="${extlinux_mbr_bin}" of="${image_file}" conv=notrunc
rmdir x-boot

losetup -d "${loop_dev}"

exit 0
