#!/bin/bash
set -euo pipefail

IMAGE_NAME="disk.img"
MOUNT_POINT="/Volumes/my_image"
TEXT_FILE="hello.txt"

# Create a blank 3MB FAT12 image (6000 * 512 bytes)
dd if=/dev/zero of="$IMAGE_NAME" bs=512 count=6000

# Attach image and get disk device
ATTACH_OUTPUT=$(hdiutil attach -nomount "$IMAGE_NAME")
DISK_DEV=$(echo "$ATTACH_OUTPUT" | grep '^/dev/disk' | awk '{print $1}')

echo "Attached as $DISK_DEV"

# Format it as FAT12
newfs_msdos -F 12 -v "XMOS DISK" "$DISK_DEV"

# Mount it to a known location
sudo mkdir -p "$MOUNT_POINT"
sudo mount -t msdos "$DISK_DEV" "$MOUNT_POINT"

echo "Mounted at $MOUNT_POINT"

# Copy txt file into the image
if [ -f "$TEXT_FILE" ]; then
    sudo cp "$TEXT_FILE" "$MOUNT_POINT/"
    echo "Copied $TEXT_FILE into image"
else
    echo "Error: $TEXT_FILE does not exist"
    exit 1
fi

# Unmount and detach
sudo umount "$MOUNT_POINT"
hdiutil detach "$DISK_DEV"

echo "Image unmounted and detached successfully."

