#!/bin/bash
# ============================================================
# JoyDock Chrome USB Debug Mode Launcher (macOS)
# Double-click to launch Chrome and open JoyDock OTA page
# Bypasses Chrome's WebUSB controlTransferOut allowlist restriction
# ============================================================

USER_DATA_DIR="$HOME/chrome-usb-test"
TARGET_URL="https://page.rayneo.com/joydock_web_ota/index_en.html"
CHROME_PATH=""

# === 1. Standard installation path ===
if [ -f "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ]; then
    CHROME_PATH="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"

# === 2. User directory installation ===
elif [ -f "$HOME/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ]; then
    CHROME_PATH="$HOME/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"

# === 3. Search via Spotlight ===
else
    CHROME_APP=$(mdfind "kMDItemCFBundleIdentifier == 'com.google.Chrome'" 2>/dev/null | head -1)
    if [ -n "$CHROME_APP" ] && [ -f "$CHROME_APP/Contents/MacOS/Google Chrome" ]; then
        CHROME_PATH="$CHROME_APP/Contents/MacOS/Google Chrome"
    fi
fi

# === Chrome not found ===
if [ -z "$CHROME_PATH" ]; then
    echo "❌ Google Chrome not found"
    echo ""
    echo "Please make sure Chrome is installed."
    echo "If Chrome is installed but still not detected, edit this script:"
    echo "  Open this file in a text editor and set CHROME_PATH to the full path of the Chrome executable"
    echo ""
    echo "Press any key to exit..."
    read -n 1
    exit 1
fi

echo "✅ Chrome found: $CHROME_PATH"
echo "Starting Chrome in USB debug mode..."
echo "  User data dir: $USER_DATA_DIR"
echo "  Target URL: $TARGET_URL"
echo ""

"$CHROME_PATH" \
    --disable-features=WebUsbEnforceStandardRequestAllowlist \
    --user-data-dir="$USER_DATA_DIR" \
    "$TARGET_URL" &

# Delay before closing terminal window
sleep 2
exit
