#!/bin/bash
# PlayTab ADB Setup (macOS / Linux)
# Downloads ADB if needed, verifies device connection.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

info()  { echo "  $*"; }
err()   { echo "  ERROR: $*" >&2; }
die()   { err "$@"; exit 1; }

# ---------------------------------------------------------------------------
# Welcome
# ---------------------------------------------------------------------------

echo ""
echo "  ============================================"
echo "   PlayTab ADB Setup"
echo "  ============================================"
echo ""
info "This script will:"
info "  1. Download ADB (Android Debug Bridge) if not installed"
info "  2. Verify the tablet is connected and authorized"
echo ""
info "Before continuing, make sure the tablet is ready:"
echo ""
info "  Step A — Enable Developer Options:"
info "    Settings > About Tablet > Build Number"
info "    Tap 'Build Number' 7 times until you see"
info "    'You are now a developer!'"
echo ""
info "  Step B — Enable USB Debugging:"
info "    Settings > Developer Options > USB Debugging (ON)"
echo ""
info "  Step C — Connect tablet via USB"
echo ""
read -p "  Press Enter when ready..."

# ---------------------------------------------------------------------------
# Find or download ADB
# ---------------------------------------------------------------------------

find_adb() {
    if command -v adb &>/dev/null; then
        ADB="adb"
        return 0
    elif [ -f "$SCRIPT_DIR/platform-tools/adb" ]; then
        ADB="$SCRIPT_DIR/platform-tools/adb"
        return 0
    fi
    return 1
}

if ! find_adb; then
    echo ""
    info "ADB not found. Downloading Android Platform Tools..."
    echo ""

    case "$(uname -s)" in
        Darwin*) PLATFORM="darwin" ;;
        Linux*)  PLATFORM="linux" ;;
        *)
            die "Unsupported OS. Please install ADB manually:
  https://developer.android.com/tools/releases/platform-tools"
            ;;
    esac

    URL="https://dl.google.com/android/repository/platform-tools-latest-${PLATFORM}.zip"
    ZIP_PATH="$SCRIPT_DIR/platform-tools.zip"

    if command -v curl &>/dev/null; then
        curl -L --connect-timeout 15 --max-time 120 -o "$ZIP_PATH" "$URL"
    elif command -v wget &>/dev/null; then
        wget --timeout=15 -O "$ZIP_PATH" "$URL"
    else
        die "Neither curl nor wget found. Cannot download.
  On macOS:  brew install android-platform-tools
  On Linux:  sudo apt install android-tools-adb"
    fi

    [ -f "$ZIP_PATH" ] || die "Download failed."

    if ! command -v unzip &>/dev/null; then
        rm -f "$ZIP_PATH"
        die "unzip is not installed. Please install it:
  On Ubuntu/Debian: sudo apt install unzip
  On Fedora/RHEL:   sudo dnf install unzip"
    fi

    info "Extracting..."
    unzip -qo "$ZIP_PATH" -d "$SCRIPT_DIR"
    rm -f "$ZIP_PATH"

    chmod +x "$SCRIPT_DIR/platform-tools/adb" 2>/dev/null
    chmod +x "$SCRIPT_DIR/platform-tools/fastboot" 2>/dev/null

    # macOS Gatekeeper: remove quarantine flag
    if [ "$(uname -s)" = "Darwin" ]; then
        xattr -dr com.apple.quarantine "$SCRIPT_DIR/platform-tools/" 2>/dev/null || true
    fi

    if ! find_adb; then
        die "ADB still not found after download."
    fi

    info "ADB installed to $SCRIPT_DIR/platform-tools/"

    # Add platform-tools to PATH in shell profile
    PLATFORM_TOOLS_PATH="$SCRIPT_DIR/platform-tools"
    EXPORT_LINE="export PATH=\"\$PATH:$PLATFORM_TOOLS_PATH\""

    if [ -f "$HOME/.zshrc" ]; then
        PROFILE="$HOME/.zshrc"
    elif [ -f "$HOME/.bashrc" ]; then
        PROFILE="$HOME/.bashrc"
    elif [ -f "$HOME/.bash_profile" ]; then
        PROFILE="$HOME/.bash_profile"
    else
        PROFILE="$HOME/.profile"
    fi

    if grep -qF "$PLATFORM_TOOLS_PATH" "$PROFILE" 2>/dev/null; then
        info "PATH already contains platform-tools (skipping profile update)."
    else
        echo "" >> "$PROFILE"
        echo "# Android Platform Tools (added by PlayTab setup)" >> "$PROFILE"
        echo "$EXPORT_LINE" >> "$PROFILE"
        info "Added ADB to PATH in $PROFILE"
        info "Run 'source $PROFILE' or open a new terminal to use adb globally."
    fi
    echo ""
fi

# ---------------------------------------------------------------------------
# Restart ADB server
# ---------------------------------------------------------------------------

info "Starting ADB server..."
$ADB kill-server 2>/dev/null || true

ADB_START_PID=""
$ADB start-server 2>/dev/null &
ADB_START_PID=$!

ADB_WAIT=0
while kill -0 "$ADB_START_PID" 2>/dev/null; do
    if [ "$ADB_WAIT" -ge 10 ]; then
        kill "$ADB_START_PID" 2>/dev/null || true
        echo ""
        die "ADB server failed to start within 10 seconds.
  This usually means another process is using port 5037.

  Try:
    killall adb 2>/dev/null; adb start-server
    or: lsof -i :5037   (to see what holds the port)"
    fi
    sleep 1
    ADB_WAIT=$((ADB_WAIT + 1))
done
wait "$ADB_START_PID" 2>/dev/null || true

# ---------------------------------------------------------------------------
# Wait for device
# ---------------------------------------------------------------------------

echo ""
info "Waiting for device (30s timeout)..."
info "Make sure the tablet is connected via USB."

WAIT_TIMEOUT=30
WAIT_START=$(date +%s)
DEVICE_FOUND=false

while true; do
    ELAPSED=$(( $(date +%s) - WAIT_START ))
    if [ "$ELAPSED" -ge "$WAIT_TIMEOUT" ]; then
        break
    fi

    DEVICE_LINE=$($ADB devices 2>/dev/null | grep -v "List of devices" | grep -v "^$" | head -1 || true)
    if [ -n "$DEVICE_LINE" ]; then
        DEVICE_FOUND=true
        break
    fi

    sleep 1
done

if [ "$DEVICE_FOUND" = false ]; then
    echo ""
    die "No device found after ${WAIT_TIMEOUT}s.

  Troubleshooting:
    - Is the USB cable a DATA cable? (not charge-only)
    - Try a different USB port
    - Is USB Debugging enabled on the tablet?
    - On Linux: you may need udev rules for your device
      sudo apt install android-tools-adb
      or add a udev rule: see https://developer.android.com/studio/run/device
    - Try: adb kill-server && adb devices"
fi

# Check authorization
ADB_STATE=$($ADB get-state 2>/dev/null || echo "unknown")
if [ "$ADB_STATE" = "unauthorized" ]; then
    echo ""
    info "*** ACTION REQUIRED ***"
    info "A dialog appeared on the tablet asking:"
    info "'Allow USB debugging from this computer?'"
    echo ""
    info "Tap ALLOW on the tablet, then press Enter here."
    read -p "  Press Enter after tapping Allow on the tablet..."

    WAIT_START=$(date +%s)
    while true; do
        ELAPSED=$(( $(date +%s) - WAIT_START ))
        if [ "$ELAPSED" -ge 15 ]; then
            break
        fi
        ADB_STATE=$($ADB get-state 2>/dev/null || echo "unknown")
        if [ "$ADB_STATE" = "device" ]; then
            break
        fi
        sleep 1
    done

    ADB_STATE=$($ADB get-state 2>/dev/null || echo "unknown")
    if [ "$ADB_STATE" != "device" ]; then
        die "Device still unauthorized.
  Make sure USB Debugging is enabled and you tapped Allow on the tablet."
    fi
fi

# Show device info
MODEL=$($ADB shell getprop ro.product.model 2>/dev/null | tr -d '\r')
ANDROID_VER=$($ADB shell getprop ro.build.version.release 2>/dev/null | tr -d '\r')
echo ""
info "Device found!"
info "Model:   $MODEL"
info "Android: $ANDROID_VER"

echo ""
echo "  ============================================"
echo "   ADB is ready. Device connected."
echo "  ============================================"
echo ""
info "You can now run playtab-install.sh to install the app."
echo ""
