#!/bin/bash

set -euo pipefail

# Find ISO and IMG files in the current working directory
mapfile -t images < <(
    find "$PWD" -maxdepth 1 -type f \
        \( -iname '*.iso' -o -iname '*.img' \) \
        -printf '%f\n' | sort
)

if ((${#images[@]} == 0)); then
    echo "No .iso or .img files found in: $PWD"
    exit 1
fi

echo "=== Select an image to flash ==="

select image in "${images[@]}"; do
    if [[ -n "${image:-}" ]]; then
        break
    fi
    echo "Invalid selection. Enter a number."
done

# Find physical disks, excluding zram and loop devices
mapfile -t devices < <(
    lsblk -dpno NAME,TYPE |
        awk '$2 == "disk" && $1 !~ /\/(zram|loop)[0-9]+$/ {
            print $1
        }'
)

if ((${#devices[@]} == 0)); then
    echo "No physical disks found."
    exit 1
fi

echo
echo "=== Select the target device ==="

for i in "${!devices[@]}"; do
    lsblk -dnpo NAME,SIZE,MODEL,TRAN "${devices[$i]}" |
        awk -v n="$((i + 1))" '{printf "%d) %s\n", n, $0}'
done

echo
read -r -p "Enter device number (1-${#devices[@]}): " choice

if [[ ! "$choice" =~ ^[0-9]+$ ]] ||
   ((choice < 1 || choice > ${#devices[@]})); then
    echo "Invalid selection. Cancelled."
    exit 1
fi

device="${devices[$((choice - 1))]}"

# Display the chosen image and target
echo
echo "Image:  $PWD/$image"
echo "Target: $device"
echo
lsblk "$device"

echo
read -r -p "ALL DATA on $device will be erased. Type YES to continue: " confirm

if [[ "$confirm" != "YES" ]]; then
    echo "Cancelled."
    exit 1
fi

# Unmount any mounted partitions on the target device
while read -r partition; do
    [[ -n "$partition" ]] || continue
    sudo umount "$partition"
done < <(
    lsblk -lnpo NAME,MOUNTPOINT "$device" |
        awk 'NF >= 2 {print $1}'
)

# Flash the image
echo
echo "Flashing image..."

sudo dd \
    if="$PWD/$image" \
    of="$device" \
    bs=4M \
    status=progress \
    conv=fsync

echo
echo "Flashing complete."
