#!/usr/bin/env bash
#
# euro - USB ISO flasher
# Copyright (C) 2026 sweden64
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See <https://www.gnu.org/licenses/>.

if [[ $EUID -ne 0 ]]; then
    echo "euro needs sudo to work properly."
    exec sudo "$0" "$@"
fi

set -euo pipefail

clear

echo "=================================="
echo "          Euro DD Flasher"
echo "=================================="
echo

echo "available storage drives:"
lsblk -d -o NAME,SIZE,MODEL,TRAN

echo

read -rp "enter the drive (e.g. sda or /dev/sda): " DRIVE
if [[ "$DRIVE" != /dev/* ]]; then
    DRIVE="/dev/$DRIVE"
fi

if [[ ! -b "$DRIVE" ]]; then
    echo
    echo "error: '$DRIVE' is not a valid device."
    exit 1
fi

echo
read -erp "enter the path to file: " ISO

ISO="${ISO/#\~/$HOME}"

if [[ ! -f "$ISO" ]]; then
    echo
    echo "error: file not found."
    exit 1
fi

echo
echo "=================================="
echo "Device : $DRIVE"
echo "ISO    : $ISO"
echo "=================================="
echo
echo "warning!"
echo "everything on $DRIVE will be permanently erased."
echo

read -rp "type YES to continue: " CONFIRM

if [[ "$CONFIRM" != "YES" ]]; then
    echo "Cancelled."
    exit 0
fi

echo
echo "unmounting any mounted partitions..."
umount "${DRIVE}"* 2>/dev/null || true

echo
echo "Flashing ISO..."
dd if="$ISO" of="$DRIVE" bs=4M status=progress oflag=direct conv=fsync

sync

echo
echo "=================================="
echo "flash complete"
echo "you may now safely eject the USB."
echo "=================================="
