#!/usr/bin/env bash
# Downloads ADB binaries for all platforms into desktop/internal/adbembed/bin/
# Run once before building for distribution.
set -e

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BIN_DIR="$ROOT/desktop/internal/adbembed/bin"
TMP=$(mktemp -d)

echo "[DroidScope] Downloading platform-tools..."

download_and_extract() {
  local os=$1
  local url=$2
  local src_name=$3
  local dest_name=$4

  echo "  → $os"
  if [[ "$url" == *.zip ]]; then
    curl -fsSL "$url" -o "$TMP/${os}.zip"
    unzip -q "$TMP/${os}.zip" "platform-tools/$src_name" -d "$TMP/${os}/"
  else
    curl -fsSL "$url" -o "$TMP/${os}.tar.gz"
    tar -xzf "$TMP/${os}.tar.gz" -C "$TMP/${os}/" "platform-tools/$src_name" 2>/dev/null || \
      tar -xzf "$TMP/${os}.tar.gz" -C "$TMP/${os}/"
  fi

  cp "$TMP/${os}/platform-tools/$src_name" "$BIN_DIR/$dest_name"
  chmod +x "$BIN_DIR/$dest_name"
}

mkdir -p "$TMP/darwin" "$TMP/linux" "$TMP/windows"

download_and_extract \
  darwin \
  "https://dl.google.com/android/repository/platform-tools-latest-darwin.zip" \
  "adb" \
  "adb-darwin-arm64"

cp "$BIN_DIR/adb-darwin-arm64" "$BIN_DIR/adb-darwin-amd64"

download_and_extract \
  linux \
  "https://dl.google.com/android/repository/platform-tools-latest-linux.zip" \
  "adb" \
  "adb-linux-amd64"

download_and_extract \
  windows \
  "https://dl.google.com/android/repository/platform-tools-latest-windows.zip" \
  "adb.exe" \
  "adb-windows-amd64.exe"

rm -rf "$TMP"
echo "[DroidScope] ADB binaries downloaded to $BIN_DIR"
ls -lh "$BIN_DIR"
