
#!/usr/bin/env bash
set -Eeuo pipefail

WIPE_SIZE_MIB=32

die() {
    echo "ERROR: $*" >&2
    exit 1
}

[[ $EUID -eq 0 ]] || die "Run this script with sudo."

for cmd in lsblk blockdev dd; do
    command -v "$cmd" >/dev/null 2>&1 ||
        die "Required command not found: $cmd"
done

# Find eMMC devices using the kernel's MMC device type.
candidates=()

for sysdev in /sys/block/mmcblk[0-9]*; do
    [[ -e "$sysdev" ]] || continue

    name=${sysdev##*/}
    [[ "$name" =~ ^mmcblk[0-9]+$ ]] || continue
    [[ -r "$sysdev/device/type" ]] || continue

    type=$(<"$sysdev/device/type")
    [[ "$type" == "MMC" ]] || continue

    candidates+=("/dev/$name")
done

((${#candidates[@]} == 1)) ||
    die "Expected exactly one eMMC, found ${#candidates[@]}."

dev=${candidates[0]}
[[ -b "$dev" ]] || die "$dev is not a block device."

size_bytes=$(blockdev --getsize64 "$dev")
wipe_bytes=$((WIPE_SIZE_MIB * 1024 * 1024))

(( size_bytes >= wipe_bytes )) ||
    die "Device is smaller than the requested erase area."

model=$(lsblk -dnro MODEL "$dev" | xargs)
size=$(lsblk -dnro SIZE "$dev")

echo
echo "Detected eMMC:"
echo "  Device: $dev"
echo "  Model:  ${model:-Unknown}"
echo "  Size:   $size"
echo
echo "WARNING: This may be the device running Linux."
echo "The operation can crash or hang the running system."
echo "The first ${WIPE_SIZE_MIB} MiB will be overwritten with zeros."
echo "Partition metadata and boot data in this area will be destroyed."
echo

read -r -p "Type WIPE $dev to continue: " answer
[[ "$answer" == "WIPE $dev" ]] ||
    die "Confirmation did not match. Nothing erased."

echo "Erasing $dev ..."

dd if=/dev/zero of="$dev" \
    bs=1M count="$WIPE_SIZE_MIB" \
    conv=fsync status=progress

sync
echo "Erase completed."
echo "Power off the board and test booting from microSD."