#!/usr/bin/env bash

# Script to write an ISO to a USB drive using dd

# Check if input and output are provided
if [ -z "$1" ] || [ -z "$2" ]; then
  echo "Usage: $0 <iso_file> <usb_drive>"
  echo "  <iso_file>: Path to the ISO file you want to write."
  echo "  <usb_drive>: Device NAME of the USB drive (e.g., sda, sdb)."
  echo "  **WARNING:** This will erase all data on the USB drive!"
  lsblk
  ls -lh
  exit 1
fi

# Check if the ISO file exists
if [ ! -f "$1" ]; then
  echo "Error: ISO file '$1' not found."
  ls -lh
  exit 1
fi

# Check if the USB drive exists
if [ ! -b "/dev/$2" ]; then
  echo "Error: USB drive '$2' not found or is not a block device."
  echo "Make sure you're using the correct device NAME (e.g., sda, sdb)."
  lsblk
  exit 1
fi

# Confirm with the user before proceeding
read -p "Are you sure you want to write '$1' to '$2'? This will erase all data on the USB drive. (y/n): " confirm

if [[ "$confirm" != "y" ]]; then
  echo "Aborted."
  exit 0
fi

# Execute the dd command
echo "Writing '$1' to '$2'..."
sudo dd bs=4M status=progress conv=fsync oflag=direct if="$1" of="/dev/$2"

# Check the exit code of the dd command
if [ $? -eq 0 ]; then
  echo "Write complete."
else
  echo "Write failed. Check for errors."
fi

#exit 0
