From ae71dc2a89d657af696eb694ce1031a8f137aa88 Mon Sep 17 00:00:00 2001
From: Johannes Schauer Marin Rodrigues <josch@mister-muffin.de>
Date: Tue, 4 Jul 2023 12:05:48 +0200
Subject: [PATCH] reform2-lpc-fw/flash.sh: make script interactive

---
 reform2-lpc-fw/flash.sh | 69 ++++++++++++++++++++++++++++++++++++-----
 1 file changed, 62 insertions(+), 7 deletions(-)

diff --git a/reform2-lpc-fw/flash.sh b/reform2-lpc-fw/flash.sh
index 0618c347..7a9dbc23 100755
--- a/reform2-lpc-fw/flash.sh
+++ b/reform2-lpc-fw/flash.sh
@@ -1,11 +1,66 @@
-#!/bin/bash
+#!/bin/sh
 
-set -e
+set -eu
 
-# replace the x with the drive that LPC actually shows up as (check dmesg -w when plugging in)
-#
-#mount /dev/sdx /mnt
-dd if=bin/firmware.bin of="/mnt/firmware.bin" conv=nocreat,notrunc
+if [ ! -e ./bin/firmware.bin ]; then
+	echo "./bin/firmware.bin doesn't exist" >&2
+	exit 1
+fi
+
+if [ "$(id -u)" -ne 0 ]; then
+	echo "you need to run this as root (for example by using sudo)" >&2
+	exit 1
+fi
+
+disk="/dev/disk/by-id/usb-NXP_LPC1XXX_IFLASH_ISP-0:0"
+
+if [ ! -e "$disk" ]; then
+	echo 'Set the DIP switch LPCPROG to “ON”.' >&2
+	echo 'Press the button LPCRESET.' >&2
+	echo 'Connect the USB cable.' >&2
+fi
+
+if [ "$(udevadm --version)" -lt 251 ]; then
+	echo 'Press the Enter key once you are ready' >&2
+	# shellcheck disable=SC2034
+	read -r enter
+else
+	echo 'Waiting for the disk to appear...' >&2
+	udevadm wait --settle "$disk"
+fi
+
+if [ "$(udevadm info --query=property --property=ID_MODEL_ID --value "$disk")" != "000b" ]; then
+	echo "unexpected model id" >&2
+	exit 1
+fi
+if [ "$(udevadm info --query=property --property=ID_VENDOR_ID --value "$disk")" != "1fc9" ]; then
+	echo "unexpected vendor id" >&2
+	exit 1
+fi
+if [ "$(udevadm info --query=property --property=ID_MODEL --value "$disk")" != "LPC1XXX_IFLASH" ]; then
+	echo "unexpected model" >&2
+	exit 1
+fi
+if [ "$(udevadm info --query=property --property=ID_VENDOR --value "$disk")" != "NXP" ]; then
+	echo "unexpected vendor" >&2
+	exit 1
+fi
+
+MOUNTPOINT="$(mktemp --tmpdir --directory reform-lpc-fw.XXXXXXXXXX)"
+trap 'umount $MOUNTPOINT' EXIT INT TERM
+mount "$disk" "$MOUNTPOINT"
+
+dd if=bin/firmware.bin of="$MOUNTPOINT/firmware.bin" conv=nocreat,notrunc
 sync
-umount "/mnt"
+umount "$MOUNTPOINT"
+trap - EXIT INT TERM
+
+echo "Firmware successfully flashed." >&2
+echo "Unplug the Micro—USB cable." >&2
+
+if [ "$(udevadm --version)" -ge 251 ]; then
+	udevadm wait --removed "$disk"
+fi
 
+echo 'Set the DIP switch LPCPROG to “OFF”.' >&2
+echo 'Press the button LPCRESET.' >&2
-- 
GitLab