#!/bin/bash

# =============================
# Script to Prepare Bootable usbboot.img for Slackware
# =============================

# Configuration
OUTPUT_IMG="usbboot.img"            # Name of the output bootable image
OUTPUT_SIZE_MB=128                  # Size of the image in MB
MBR_BIN="/usr/share/syslinux/mbr.bin" # Path to the MBR binary
SYSLINUX_BIN="/usr/bin/syslinux"    # Path to the Syslinux binary
SOURCE_DIR="./newflas"              # Directory containing boot files
WORK_DIR="/mnt/usbboot"             # Temporary mount directory

# Step 1: Create an empty image file
echo "[INFO] Creating a bootable image: $OUTPUT_IMG"
dd if=/dev/zero of="$OUTPUT_IMG" bs=1M count="$OUTPUT_SIZE_MB" status=progress

# Step 2: Write the MBR to the image
echo "[INFO] Writing MBR to the image..."
dd if="$MBR_BIN" of="$OUTPUT_IMG" bs=440 count=1 conv=notrunc

# Step 3: Create a partition table and a single FAT32 partition
echo "[INFO] Creating partition table and FAT32 partition..."
parted -s "$OUTPUT_IMG" mklabel msdos
parted -s "$OUTPUT_IMG" mkpart primary fat32 1MiB 100%
parted -s "$OUTPUT_IMG" set 1 boot on

# Step 4: Set up a loopback device with partitions
echo "[INFO] Setting up loopback device for $OUTPUT_IMG..."
LOOP_DEVICE=$(losetup -fP --show "$OUTPUT_IMG")
PARTITION="${LOOP_DEVICE}p1"

# Step 5: Format the partition with FAT32
echo "[INFO] Formatting the partition with FAT32..."
mkfs.fat -F 32 "$PARTITION"

# Step 6: Mount the partition
echo "[INFO] Mounting the partition..."
mkdir -p "$WORK_DIR"
mount "$PARTITION" "$WORK_DIR"

# Step 7: Copy files from the source directory to the partition
echo "[INFO] Copying files from $SOURCE_DIR to the partition..."
cp -r "$SOURCE_DIR/"* "$WORK_DIR/"

# Step 8: Unmount the partition
echo "[INFO] Unmounting the partition..."
umount "$WORK_DIR"

# Step 9: Install Syslinux bootloader on the partition
echo "[INFO] Installing Syslinux bootloader..."
"$SYSLINUX_BIN" "$PARTITION"

# Step 10: Detach the loopback device
echo "[INFO] Detaching loopback device..."
losetup -d "$LOOP_DEVICE"

# Clean up the mount directory
rmdir "$WORK_DIR"

# Final message
echo "[INFO] usbboot.img created successfully with Syslinux."
