#!/usr/bin/env bash
# Elementic STM32F103 Blue Pill — Serasidis HID bootloader installer
# Run: bash install-linux.sh [SWD_SPEED_KHZ]
set -Eeuo pipefail
speed="${1:-1000}"
if [[ ! "$speed" =~ ^[0-9]+$ ]] || (( speed < 50 || speed > 8000 )); then
  echo 'ERROR: SWD speed must be an integer between 50 and 8000 kHz.' >&2; exit 1
fi
version='2.2.2'
url="https://github.com/Serasidis/STM32_HID_Bootloader/releases/download/${version}/stm32_binaries.zip"
workdir="${HOME}/Elementic/Bootloader"
mkdir -p "$workdir"
archive="${workdir}/stm32_binaries.zip"
bin="${workdir}/hid_generic_pc13.bin"
for cmd in curl unzip; do
  command -v "$cmd" >/dev/null || { echo "ERROR: Install '$cmd' first." >&2; exit 1; }
done
printf '[1/4] Downloading Serasidis %s ...\n' "$version"
curl --fail --location --retry 2 --show-error --silent "$url" --output "$archive"
# The release archive contains the board-specific binary at this documented path.
entry="$(unzip -Z -1 "$archive" | grep -E '(^|/)F103/low_and_medium_density/hid_generic_pc13\.bin$' | head -n 1 || true)"
[[ -n "$entry" ]] || { echo 'ERROR: Expected Blue Pill image not found in archive.' >&2; exit 1; }
unzip -p "$archive" "$entry" > "$bin"
[[ -s "$bin" ]] || { echo 'ERROR: Bootloader image is empty.' >&2; exit 1; }

printf '[2/4] Preparing OpenOCD ...\n'
pio_root="${PLATFORMIO_CORE_DIR:-${HOME}/.platformio}"
openocd_dir="${pio_root}/packages/tool-openocd"
openocd="${openocd_dir}/bin/openocd"
if [[ ! -x "$openocd" ]]; then
  command -v pio >/dev/null || { echo 'ERROR: PlatformIO Core (pio) not found. Install it first.' >&2; exit 1; }
  pio pkg install -g -t 'platformio/tool-openocd'
fi
[[ -x "$openocd" ]] || { echo "ERROR: OpenOCD executable not found at $openocd" >&2; exit 1; }

printf '[3/4] Flashing and verifying through ST-Link ...\n'
"$openocd" \
  -s "$openocd_dir/scripts" \
  -f interface/stlink.cfg \
  -c 'transport select swd' \
  -c "adapter speed $speed" \
  -f target/stm32f1x.cfg \
  -c "program {$bin} verify reset exit 0x08000000"
printf '[4/4] Bootloader flashed and verified successfully.\n'
printf 'Set BOOT0=0. Reconnect USB and look for HID VID_1209 PID_BEBA.\n'
