@echo off
title PlayTab ADB Setup
color 0A
setlocal enabledelayedexpansion

echo.
echo  ============================================
echo   PlayTab ADB Setup
echo  ============================================
echo.
echo  This script will:
echo    1. Download ADB (Android Debug Bridge) if not installed
echo    2. Verify the tablet is connected and authorized
echo.
echo  Before continuing, make sure the tablet is ready:
echo.
echo    Step A - Enable Developer Options:
echo      Settings ^> About Tablet ^> Build Number
echo      Tap 'Build Number' 7 times until you see
echo      'You are now a developer!'
echo.
echo    Step B - Enable USB Debugging:
echo      Settings ^> Developer Options ^> USB Debugging (ON)
echo.
echo    Step C - Connect tablet via USB
echo.
echo    Step D - Install USB driver (if needed):
echo      If the tablet is not detected, you may need a driver.
echo      Download Universal ADB Driver from:
echo        https://adb.clockworkmod.com
echo      or install your tablet manufacturer's USB driver.
echo.
pause

:: ---------------------------------------------------------------------------
:: Find or download ADB
:: ---------------------------------------------------------------------------

set "ADB="
where adb >nul 2>nul
if %errorlevel% equ 0 (
    set "ADB=adb"
    goto :adb_found
)
if exist "%~dp0platform-tools\adb.exe" (
    set "ADB=%~dp0platform-tools\adb.exe"
    goto :adb_found
)

:: ADB not found — download it
echo.
echo  ADB not found. Downloading Android Platform Tools...
echo.

where curl >nul 2>nul
if %errorlevel% neq 0 (
    echo  ERROR: curl not found. Cannot download automatically.
    echo.
    echo  Please download Android Platform Tools manually:
    echo    1. Go to: https://developer.android.com/tools/releases/platform-tools
    echo    2. Download the Windows zip
    echo    3. Extract the 'platform-tools' folder next to this script
    echo    4. Run this script again
    echo.
    pause
    exit /b 1
)

curl -L --connect-timeout 15 --max-time 120 --progress-bar -o "%~dp0platform-tools.zip" "https://dl.google.com/android/repository/platform-tools-latest-windows.zip"
if not exist "%~dp0platform-tools.zip" (
    echo  ERROR: Download failed. Check your internet connection.
    pause
    exit /b 1
)

echo  Extracting...
powershell -ExecutionPolicy Bypass -Command "Expand-Archive -Force '%~dp0platform-tools.zip' '%~dp0'" 2>nul
if %errorlevel% neq 0 (
    echo  ERROR: Extraction failed. Make sure PowerShell is available.
    del "%~dp0platform-tools.zip" >nul 2>nul
    pause
    exit /b 1
)
del "%~dp0platform-tools.zip" >nul 2>nul

if exist "%~dp0platform-tools\adb.exe" (
    set "ADB=%~dp0platform-tools\adb.exe"
    echo  ADB installed to %~dp0platform-tools\
    echo.
    set "PATH=!PATH!;%~dp0platform-tools"
    echo  ADB added to this session's PATH.
    echo  To use adb globally, add this folder to your system PATH:
    echo    %~dp0platform-tools
    echo.
) else (
    echo  ERROR: ADB still not found after download.
    pause
    exit /b 1
)

:adb_found

:: ---------------------------------------------------------------------------
:: Restart ADB server
:: ---------------------------------------------------------------------------

echo.
echo  Starting ADB server...
%ADB% kill-server >nul 2>nul

:: start-server can hang — timeout after 10s
start /b "" cmd /c "%ADB% start-server >nul 2>nul && echo done >%TEMP%\playtab_adb_ok.txt"
del "%TEMP%\playtab_adb_ok.txt" >nul 2>nul
set ADB_WAIT=0
:adb_start_loop
if exist "%TEMP%\playtab_adb_ok.txt" goto :adb_started
if !ADB_WAIT! geq 10 (
    echo.
    echo  ERROR: ADB server failed to start within 10 seconds.
    echo  This usually means another process is using port 5037.
    echo.
    echo  Try:
    echo    taskkill /f /im adb.exe 2^>nul ^& adb start-server
    echo    or: netstat -ano ^| findstr 5037
    echo.
    pause
    exit /b 1
)
timeout /t 1 /nobreak >nul
set /a ADB_WAIT+=1
goto :adb_start_loop
:adb_started
del "%TEMP%\playtab_adb_ok.txt" >nul 2>nul

:: ---------------------------------------------------------------------------
:: Wait for device
:: ---------------------------------------------------------------------------

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

set WAIT_COUNT=0
set DEVICE_FOUND=0

:wait_loop
if !WAIT_COUNT! geq 30 goto :wait_done

for /f "skip=1 tokens=1" %%d in ('%ADB% devices 2^>nul') do (
    if not "%%d"=="" (
        set DEVICE_FOUND=1
        goto :wait_done
    )
)

timeout /t 1 /nobreak >nul
set /a WAIT_COUNT+=1
goto :wait_loop

:wait_done

if !DEVICE_FOUND! equ 0 (
    echo.
    echo  ERROR: No device found after 30 seconds.
    echo.
    echo  Troubleshooting:
    echo    - Is the USB cable a DATA cable? ^(not charge-only^)
    echo    - Try a different USB port
    echo    - Is USB Debugging enabled on the tablet?
    echo    - You may need a USB driver. Download from:
    echo        https://adb.clockworkmod.com  ^(Universal ADB Driver^)
    echo      or your tablet manufacturer's website
    echo    - Try: adb kill-server ^&^& adb devices
    echo.
    pause
    exit /b 1
)

:: Check authorization
for /f "tokens=*" %%i in ('%ADB% get-state 2^>nul') do set ADB_STATE=%%i
if "!ADB_STATE!"=="unauthorized" (
    echo.
    echo  *** ACTION REQUIRED ***
    echo  A dialog appeared on the tablet asking:
    echo  'Allow USB debugging from this computer?'
    echo.
    echo  Tap ALLOW on the tablet, then press any key here.
    pause >nul

    set AUTH_COUNT=0
    :auth_loop
    if !AUTH_COUNT! geq 15 goto :auth_done
    for /f "tokens=*" %%i in ('%ADB% get-state 2^>nul') do set ADB_STATE=%%i
    if "!ADB_STATE!"=="device" goto :auth_done
    timeout /t 1 /nobreak >nul
    set /a AUTH_COUNT+=1
    goto :auth_loop
    :auth_done

    if not "!ADB_STATE!"=="device" (
        echo  ERROR: Device still unauthorized.
        echo  Make sure USB Debugging is enabled and you tapped Allow on the tablet.
        pause
        exit /b 1
    )
)

echo.
echo  Device found!
for /f "tokens=*" %%i in ('%ADB% shell getprop ro.product.model') do set MODEL=%%i
for /f "tokens=*" %%i in ('%ADB% shell getprop ro.build.version.release') do set ANDROID_VER=%%i
echo  Model:   %MODEL%
echo  Android: %ANDROID_VER%

echo.
echo  ============================================
echo   ADB is ready. Device connected.
echo  ============================================
echo.
echo  You can now run playtab-install.bat to install the app.
echo.
pause
