#!/bin/sh
# make_floppy.sh -- Create a virtual floppy disk image with given files
# Usage: make_floppy.sh <output.img> <file1> [file2] ...
# POSIX sh compatible (busybox/ash/dash)

set -eu

OUTPUT="${1:-}"
shift || true

if [ -z "$OUTPUT" ] || [ $# -eq 0 ]; then
    echo "Usage: make_floppy.sh <output.img> <file1> [file2] ..." >&2
    exit 1
fi

. /hiperiso-lib.sh

_total_size=0
for f in "$@"; do
    if [ -f "$f" ]; then
        _sz=$(wc -c < "$f" 2>/dev/null || echo 0)
        _total_size=$((_total_size + _sz))
    fi
done

if [ "$_total_size" -gt 2621440 ]; then
    _floppy_size=2880
else
    _floppy_size=1440
fi

dd if=/dev/zero of="$OUTPUT" bs=1024 count=$_floppy_size 2>/dev/null

if command -v mkfs.vfat >/dev/null 2>&1; then
    mkfs.vfat -F 12 -n HIPERISO "$OUTPUT" >/dev/null 2>&1
elif command -v mkdosfs >/dev/null 2>&1; then
    mkdosfs -F 12 -n HIPERISO "$OUTPUT" >/dev/null 2>&1
else
    hiperiso_log "WARNING: no FAT formatter available, floppy image is blank"
    exit 1
fi

_mnt=$(mktemp -d /tmp/floppy.XXXXXX 2>/dev/null || echo /tmp/floppy_mnt)
mkdir -p "$_mnt"

if mount -o loop "$OUTPUT" "$_mnt" 2>/dev/null; then
    for f in "$@"; do
        if [ -f "$f" ]; then
            cp "$f" "$_mnt/" 2>/dev/null || true
        fi
    done
    sync
    umount "$_mnt" 2>/dev/null || true
else
    if command -v mcopy >/dev/null 2>&1; then
        for f in "$@"; do
            if [ -f "$f" ]; then
                mcopy -i "$OUTPUT" "$f" ::/ 2>/dev/null || true
            fi
        done
    else
        hiperiso_log "WARNING: cannot mount loop or use mtools, floppy is empty"
    fi
fi

rmdir "$_mnt" 2>/dev/null || true
exit 0
