#!/bin/bash
#
# AIPI Mac backup tool — saves a full 16 MB backup of your AIPI to the Desktop
# without going through the browser.
#
# Why this exists: the browser-based backup on Mac keeps failing on ESP32
# chips' built-in USB ports — the flasher's helper program drops the data
# stream. This tool uses esptool's --no-stub mode (a stable mode that does not
# rely on that helper), which is slower but reliable.
#
# Works with AIPI Lite and AIPI Lite EVO alike: the flash size is detected
# from the device itself (4, 8 or 16 MB), and the whole flash is saved.
#
# Usage: double-click this file (or run `bash mac-backup-tool.command` in
# Terminal). If macOS blocks it, open System Settings → Privacy & Security
# and click Open Anyway.

set -u

ESPTOOL_VERSION="v4.8.0"
TAR_BASE="https://github.com/espressif/esptool/releases/download/${ESPTOOL_VERSION}"

bold() { printf '\033[1m%s\033[0m\n' "$1"; }
note() { printf '  %s\n' "$1"; }

bold "AIPI Mac backup tool"
printf 'This saves a full backup of your AIPI system to your Desktop,\n'
printf 'so you can always switch back to it later.\n\n'

# --- 1. Find or fetch esptool -------------------------------------------------

download_esptool() {
  local dir bin status rc errfile tried name
  dir="$(mktemp -d)"
  errfile="${dir}/curl.err"
  tried=""
  # The official v4.8.0 macOS asset is one architecture-neutral zip; the two
  # per-arch tarballs below never existed upstream, but stay as fallbacks in
  # case a mirror publishes them under those names.
  for name in \
    "esptool-${ESPTOOL_VERSION}-macos.zip" \
    "esptool-${ESPTOOL_VERSION}-macos-arm64.tar.gz" \
    "esptool-${ESPTOOL_VERSION}-macos-amd64.tar.gz"
  do
    note "Downloading the official esptool (${ESPTOOL_VERSION})..."
    note "Trying: ${TAR_BASE}/${name}"
    status="$(curl -fSL --connect-timeout 15 -o "${dir}/${name}" -w '%{http_code}' "${TAR_BASE}/${name}" 2>"$errfile")"
    rc=$?
    if [ "$rc" -ne 0 ]; then
      note "Failed: HTTP ${status:-?} from ${TAR_BASE}/${name}"
      if [ -s "$errfile" ]; then
        sed 's/^/  curl: /' "$errfile"
      fi
      tried="${tried}  ${TAR_BASE}/${name}
"
      continue
    fi
    case "$name" in
      *.zip) unzip -o "${dir}/${name}" -d "$dir" ;;
      *)     tar -xzf "${dir}/${name}" -C "$dir" ;;
    esac
    bin="$(find "$dir" -type f -name esptool | head -n 1)"
    if [ -n "$bin" ]; then
      chmod +x "$bin"
      run_esptool() { "$bin" "$@"; }
      note "esptool ready."
      return 0
    fi
    note "Failed: no esptool binary inside the downloaded archive."
    tried="${tried}  ${TAR_BASE}/${name}
"
  done
  note "Tried:"
  printf '%s' "$tried"
  rm -rf "$dir"
  return 1
}

pip_install_esptool() {
  command -v python3 >/dev/null 2>&1 || return 1
  command -v pip3 >/dev/null 2>&1 || return 1
  note "Falling back to installing esptool with pip (one-time, about a minute)..."
  pip3 install --user esptool >/dev/null 2>&1 || return 1
  # pip installs the entry point into ~/Library/Python/*/bin on macOS, which is
  # not always on PATH — run through the Python module instead.
  python3 -m esptool --version >/dev/null 2>&1 || return 1
  run_esptool() { python3 -m esptool "$@"; }
  note "esptool installed."
}

# run_esptool is defined by whichever source wins: an installed esptool, the
# esptool Python module, the downloaded official binary, or a pip install.
if command -v esptool >/dev/null 2>&1; then
  run_esptool() { esptool "$@"; }
  note "Using the esptool already installed on this Mac."
elif command -v python3 >/dev/null 2>&1 && python3 -m esptool --version >/dev/null 2>&1; then
  run_esptool() { python3 -m esptool "$@"; }
  note "Using the esptool Python module already installed."
elif ! download_esptool && ! pip_install_esptool; then
  bold "Couldn't get the backup tool ready."
  note "You need either a network connection to download it, or Python 3"
  note "installed from https://www.python.org/downloads/ so it can be installed."
  note "Then run this file again. If it still fails, email support."
  note "The download attempts and their errors are printed above."
  exit 1
fi

# --- 2. Plug in the AIPI -------------------------------------------------------

bold "Plug your AIPI into this Mac with its USB cable now."
printf 'Once it is plugged in, wait about 30 seconds for it to finish\n'
printf 'starting up (especially the AIPI Lite EVO), then press Enter to continue: '
read -r _

# esptool finds the port on its own when none is given — no guessing needed.

# --- 3. Read the flash size and the device code --------------------------------

bold "Reading your AIPI's details..."
ERRFILE="$(mktemp)"
INFO="$(set -o pipefail; run_esptool --no-stub flash_id 2>"$ERRFILE" | tr -d '\r')" || {
  bold "Your AIPI didn't answer."
  if [ -s "$ERRFILE" ]; then
    note "esptool reported:"
    head -n 12 "$ERRFILE" | sed 's/^/  /'
  fi
  PORTS="$(ls /dev/cu.usbmodem* 2>/dev/null)"
  if [ -n "$PORTS" ]; then
    note "USB ports on this Mac:"
    printf '%s\n' "$PORTS" | sed 's/^/  /'
  else
    note "No USB port named /dev/cu.usbmodem* was found."
  fi
  note "Try these, then run this file again:"
  note "- Use the cable that came with the AIPI (a charge-only cable won't work)."
  note "- Plug it straight into the Mac, not into a hub or adapter."
  note "- Close any other page or app that might be talking to the AIPI."
  note "- Quit Chrome completely — Chrome holds the USB port even in the background."
  note "- If this is the first time: macOS may ask to allow USB access — allow it."
  exit 1
}
rm -f "$ERRFILE"

SIZE_LABEL="$(printf '%s\n' "$INFO" | grep -o 'Detected flash size: [0-9]*[KM]*B' | head -n 1 |
  sed 's/Detected flash size: //')"
MAC="$(printf '%s\n' "$INFO" | grep -o 'MAC: [0-9a-f:]*' | head -n 1 | sed 's/MAC: //')"
if [ -z "$SIZE_LABEL" ] || [ -z "$MAC" ]; then
  bold "This doesn't look like an AIPI."
  note "The device on the cable didn't report a flash size and address."
  note "Unplug other devices and run this file again."
  exit 1
fi

case "$SIZE_LABEL" in
  4MB)  SIZE=0x400000 ;;
  8MB)  SIZE=0x800000 ;;
  16MB) SIZE=0x1000000 ;;
  *)
    bold "This AIPI's storage size ($SIZE_LABEL) isn't one this tool knows."
    note "Email support and include this line — a backup will be arranged."
    exit 1
    ;;
esac

CODE="$(printf '%s' "$MAC" | awk -F: '{ printf "%s%s%s", toupper($4), toupper($5), toupper($6) }')"
OUT="$HOME/Desktop/aipi-backup-${CODE}.bin"

# --- 4. Save the backup ---------------------------------------------------------

bold "Backing up now — this is the slow part."
printf 'The backup is %s. On Mac it takes 30+ minutes; please\n' "$SIZE_LABEL"
printf 'keep the AIPI plugged in and this window open until it finishes.\n\n'

if ! run_esptool --no-stub read_flash 0x0 "$SIZE" "$OUT"; then
  bold "The backup didn't finish."
  note "Nothing on your AIPI was changed — try these, then run this file again:"
  note "- Use the cable that came with the AIPI, plugged straight into the Mac."
  note "- Quit other apps that might use the port, and keep the window in the foreground."
  note "- If it stops at the same place every time, note the address and email support."
  exit 1
fi

bold "Backup saved."
printf '  Your file: %s\n' "$OUT"
printf '  Keep this file safe — it is the way back to the AIPI system as it was today.\n\n'
bold "Next step"
printf 'Go back to the setup page in your browser and click\n'
printf '"Skip the backup — install Muse now". No backup file is asked for;\n'
printf 'the install proceeds right away.\n'
