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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PORT="${PORT:-/dev/ttyACM0}"
ESPTOOL="${ESPTOOL:-$HOME/.arduino15/packages/esp32/tools/esptool_py/5.1.0/esptool}"
IN_BIN="${IN_BIN:-${ROOT_DIR}/factory-full-16mb.bin}"

if [[ ! -f "${IN_BIN}" ]]; then
  echo "Backup file not found: ${IN_BIN}" >&2
  exit 1
fi

echo "== Port: ${PORT}"
echo "== Input: ${IN_BIN}"
echo "== Esptool: ${ESPTOOL}"

"${ESPTOOL}" --port "${PORT}" --baud 921600 write-flash 0 "${IN_BIN}"

echo
echo "== Restore done."
