#!/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
kernel="${outdir}/src/bringelle"

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

check_for losetup
[ ! -e "$floppy" ] && { echo "Floppy drive \"$floppy\" not found!"; exit 1; }
[ ! -e "$kernel" ] && { echo "Kernel \"$kernel\" not found!"; exit 1; }

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

# Prepare disk partition
sudo mount $part "$mountp"
cp $kernel $mountp/boot/bringelle.bs

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

# Cleanup
sudo losetup -D