#!/usr/bin/env bash

# Ensure to abort on error
set -e

wai=$(dirname $(readlink -f "$0")) # Current script directory
outdir="${wai}/../"
floppy="${outdir}/floppy.img"
mountp="$(mktemp -d)" # Mount point (where the floppy will be mounted temporally
sysbios="/usr/lib/syslinux/bios/" # Syslinux bios and ui locations

check_for () {
    command -v "$1" &>/dev/null || { echo "Command $1 not found!"; exit 1; }
}

check_for parted
check_for losetup
check_for extlinux
check_for mkfs.ext4
[ -d "$sysbios" ] || { echo "Syslinux bios \"$sysbios\" not found!"; exit 1; }

# Create drive
dd if=/dev/zero of=${floppy} bs=512 count=50000 # Change count to change floppy size :)
parted -s $floppy mklabel gpt
parted -s $floppy mkpart linux ext4 0 100%
parted -s $floppy set 1 legacy_boot on # Require for syslinux according to https://wiki.gentoo.org/wiki/Syslinux#GPT

# Initiate loop devices
loop=$(sudo losetup -f)
part="${loop}p1" # Disk partition
sudo losetup -Pf $floppy

# Prepare disk partition
sudo mkfs.ext4 $part
sudo mount $part "$mountp"
sudo mkdir -p $mountp/boot/syslinux/

# Configuring syslinux
sudo chown -R loic $mountp/boot/
cfg=$(mktemp)
cat > "$cfg" <<EOF
TIMEOUT 30
UI vesamenu.c32

MENU TITLE Syslinux
 LABEL Bringelle
 KERNEL /boot/bringelle.bs
EOF
mv "$cfg" "$mountp/boot/syslinux/syslinux.cfg"
cp $sysbios/*.c32 $mountp/boot/syslinux/
sudo extlinux --install $mountp/boot/syslinux

# Umount floppy
sync
sudo umount "$mountp"
rmdir "$mountp"

# Install MBR
sudo dd bs=440 count=1 conv=notrunc if=$sysbios/gptmbr.bin of=${loop}

# Cleanup
sudo losetup -D