@echo off
chcp 65001 >nul
setlocal EnableExtensions
cd /d "%~dp0"

echo ============================================================
echo OK ITHAKI ANDROID V249571 - CLEAN APK BUILD
echo ============================================================

if not exist "gradlew.bat" (
  echo ERROR_GRADLEW_NOT_FOUND
  pause
  exit /b 1
)

if not defined JAVA_HOME (
  if exist "%ProgramFiles%\Android\Android Studio\jbr\bin\java.exe" set "JAVA_HOME=%ProgramFiles%\Android\Android Studio\jbr"
)
if not defined JAVA_HOME (
  if exist "%LOCALAPPDATA%\Programs\Android Studio\jbr\bin\java.exe" set "JAVA_HOME=%LOCALAPPDATA%\Programs\Android Studio\jbr"
)
if not defined JAVA_HOME (
  where java >nul 2>&1 || (
    echo ERROR_JAVA_NOT_FOUND
    echo Open Android Studio once or install JDK 17/21.
    pause
    exit /b 1
  )
)

if not defined ANDROID_HOME if exist "%LOCALAPPDATA%\Android\Sdk" set "ANDROID_HOME=%LOCALAPPDATA%\Android\Sdk"
if not defined ANDROID_SDK_ROOT if defined ANDROID_HOME set "ANDROID_SDK_ROOT=%ANDROID_HOME%"

if defined JAVA_HOME echo JAVA_HOME=%JAVA_HOME%
if defined ANDROID_HOME echo ANDROID_HOME=%ANDROID_HOME%

call gradlew.bat --stop >nul 2>&1
call gradlew.bat clean assembleDebug
if errorlevel 1 (
  echo APK_BUILD_FAILED
  pause
  exit /b 1
)

set "APK=app\build\outputs\apk\debug\app-debug.apk"
if not exist "%APK%" (
  echo APK_NOT_FOUND
  pause
  exit /b 1
)

echo APK_BUILD_V249571=OK
echo APK_PATH=%CD%\%APK%

set "ADB=%LOCALAPPDATA%\Android\Sdk\platform-tools\adb.exe"
if not exist "%ADB%" set "ADB=adb"
where "%ADB%" >nul 2>&1
if errorlevel 1 goto :NO_INSTALL

for /f "skip=1 tokens=1,2" %%A in ('"%ADB%" devices 2^>nul') do (
  if "%%B"=="device" goto :INSTALL
)
goto :NO_INSTALL

:INSTALL
"%ADB%" install -r "%APK%"
if errorlevel 1 (
  echo APK_BUILT_BUT_INSTALL_FAILED
  echo APK_PATH=%CD%\%APK%
  pause
  exit /b 0
)
echo APK_BUILD_INSTALL_V249571=OK
pause
exit /b 0

:NO_INSTALL
echo APK_BUILT_NO_AUTHORIZED_DEVICE=YES
echo Connect and authorize the phone, then install the APK shown above.
pause
exit /b 0
