#! /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. Downloading a static Tclkit with TUAPI
#  4. Downloading a static AppFS

make init LDFLAGS=-static
cp init root/bin

rm -f appfs.img
truncate --size 1024M appfs.img
sfdisk --no-tell-kernel --no-reread ./appfs.img <<<'label: dos
size=16M type=83 bootable
size=239M type=83
type=83'

sudo umount x-boot || :
sudo losetup -d /dev/loop3 || :
sudo losetup --partscan /dev/loop3 $(pwd)/appfs.img
sudo chown "$(id -u):$(id -g)" /dev/loop3 /dev/loop3p1 /dev/loop3p2

sudo mke2fs \
  -L 'BOOT' \
  -N 0 \
  -O ^64bit \
  -d boot \
  -m 5 \
  -r 1 \
  -t ext4 \
  /dev/loop3p1

sudo mke2fs \
  -L 'ROOT' \
  -N 0 \
  -O ^64bit \
  -d root \
  -m 5 \
  -r 1 \
  -t ext4 \
  /dev/loop3p2

sudo mke2fs \
  -L 'DATA' \
  -N 0 \
  -O ^64bit \
  -m 5 \
  -r 1 \
  -t ext4 \
  /dev/loop3p3

mkdir x-boot || :
sudo mount /dev/loop3p1 x-boot
sudo extlinux --install $(pwd)/x-boot
sudo umount x-boot
dd if=/usr/lib/EXTLINUX/mbr.bin of=appfs.img conv=notrunc
rmdir x-boot

losetup -d /dev/loop3
