@echo off
title PlayTab App Install
color 0A
setlocal enabledelayedexpansion

echo.
echo  ============================================
echo   PlayTab App Install
echo  ============================================
echo.

set "PKG=com.symflo.playtab"
set "ADMIN_RECEIVER=%PKG%/.PlayTabDeviceAdminReceiver"

:: ---------------------------------------------------------------------------
:: Check ADB + device
:: ---------------------------------------------------------------------------

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

echo  ERROR: ADB not found. Run playtab-adb.bat first.
pause
exit /b 1

:adb_ok

for /f "tokens=*" %%i in ('%ADB% get-state 2^>nul') do set ADB_STATE=%%i
if not "!ADB_STATE!"=="device" (
    echo  ERROR: No authorized device connected ^(state: !ADB_STATE!^).
    echo  Make sure the tablet is plugged in and run playtab-adb.bat if needed.
    pause
    exit /b 1
)

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  Device: %MODEL% (Android %ANDROID_VER%)

:: ---------------------------------------------------------------------------
:: Step 1: Download latest APK
:: ---------------------------------------------------------------------------

echo.
echo  Step 1: Fetching latest version...

curl -s --connect-timeout 10 --max-time 30 -o "%TEMP%\playtab_manifest.json" "https://api.symflofi.cloud/updates/playtab/manifest.json"
if not exist "%TEMP%\playtab_manifest.json" (
    echo  ERROR: Could not fetch manifest. Check your internet connection.
    pause
    exit /b 1
)

for %%A in ("%TEMP%\playtab_manifest.json") do if %%~zA equ 0 (
    echo  ERROR: Manifest file is empty. The server may be down.
    del "%TEMP%\playtab_manifest.json" >nul 2>nul
    pause
    exit /b 1
)

for /f "tokens=*" %%i in ('powershell -ExecutionPolicy Bypass -Command "(Get-Content '%TEMP%\playtab_manifest.json' -Raw | ConvertFrom-Json).latest" 2^>nul') do set LATEST=%%i
for /f "tokens=*" %%i in ('powershell -ExecutionPolicy Bypass -Command "$m = Get-Content '%TEMP%\playtab_manifest.json' -Raw | ConvertFrom-Json; $v = $m.latest; $m.releases.$v.apk.url" 2^>nul') do set APK_URL=%%i
for /f "tokens=*" %%i in ('powershell -ExecutionPolicy Bypass -Command "$m = Get-Content '%TEMP%\playtab_manifest.json' -Raw | ConvertFrom-Json; $v = $m.latest; $m.releases.$v.apk.sha256" 2^>nul') do set APK_SHA=%%i
del "%TEMP%\playtab_manifest.json" >nul 2>nul

if "%LATEST%"=="" (
    echo  ERROR: Could not parse manifest.
    echo  Make sure PowerShell is available and internet is connected.
    pause
    exit /b 1
)

echo  Latest version: v%LATEST%

set "APK_PATH=%~dp0playtab-%LATEST%.apk"
set "FULL_URL=https://api.symflofi.cloud/updates/%APK_URL%"

:: Check if we already have a valid APK
if exist "%APK_PATH%" (
    if not "%APK_SHA%"=="" (
        for /f "tokens=*" %%i in ('powershell -ExecutionPolicy Bypass -Command "(Get-FileHash '%APK_PATH%' -Algorithm SHA256).Hash.ToLower()" 2^>nul') do set EXISTING_SHA=%%i
        if /i "!EXISTING_SHA!"=="%APK_SHA%" (
            echo  APK already downloaded ^(checksum matches^).
            goto :install
        )
    )
)

echo  Downloading PlayTab v%LATEST%...
curl -L --connect-timeout 15 --max-time 300 --progress-bar -o "%APK_PATH%" "%FULL_URL%"
if not exist "%APK_PATH%" (
    echo  ERROR: APK download failed.
    pause
    exit /b 1
)

:: Verify checksum
if not "%APK_SHA%"=="" (
    for /f "tokens=*" %%i in ('powershell -ExecutionPolicy Bypass -Command "(Get-FileHash '%APK_PATH%' -Algorithm SHA256).Hash.ToLower()" 2^>nul') do set ACTUAL_SHA=%%i
    if /i not "!ACTUAL_SHA!"=="%APK_SHA%" (
        echo  ERROR: Checksum mismatch! APK may be corrupted.
        echo  Expected: %APK_SHA%
        echo  Got:      !ACTUAL_SHA!
        del "%APK_PATH%" >nul 2>nul
        echo  The file has been deleted. Please run the script again.
        pause
        exit /b 1
    )
    echo  Checksum verified.
)

:: ---------------------------------------------------------------------------
:: Step 2: Install APK
:: ---------------------------------------------------------------------------

:install
echo.
echo  Step 2: Installing PlayTab v%LATEST%...

%ADB% shell pm list packages 2>nul | findstr /C:"%PKG%" >nul 2>nul
if %errorlevel% equ 0 (
    echo  PlayTab is already installed. Attempting upgrade...
    %ADB% install -r "%APK_PATH%" >"%TEMP%\playtab_install.txt" 2>&1
    if %errorlevel% neq 0 (
        findstr /i /C:"INSTALL_FAILED_UPDATE_INCOMPATIBLE" /C:"INCONSISTENT_CERTIFICATES" /C:"signatures do not match" "%TEMP%\playtab_install.txt" >nul 2>nul
        if %errorlevel% equ 0 (
            echo.
            echo  The installed version was signed with a different key.
            echo  This happens when switching between debug and release builds.
            echo.

            %ADB% shell dumpsys device_policy 2>nul | findstr /C:"%PKG%" >nul 2>nul
            if %errorlevel% equ 0 (
                echo  PlayTab is currently set as device owner.
                echo  To reinstall, we need to:
                echo    1. Clear device owner
                echo    2. Uninstall the old version
                echo    3. Install the new version
                echo    4. Re-set device owner
                echo.
                set /p "REPLY=  Continue? (y/N) "
                if /i not "!REPLY!"=="y" (
                    echo  Aborted.
                    del "%TEMP%\playtab_install.txt" >nul 2>nul
                    pause
                    exit /b 0
                )

                echo  Clearing device owner...
                %ADB% shell dpm remove-active-admin "%ADMIN_RECEIVER%" >nul 2>nul
            )

            echo  Uninstalling old version...
            %ADB% uninstall "%PKG%" >nul 2>nul

            echo  Installing PlayTab v%LATEST% ^(fresh install^)...
            %ADB% install "%APK_PATH%" >"%TEMP%\playtab_install.txt" 2>&1
            if %errorlevel% neq 0 (
                echo  ERROR: Installation failed.
                type "%TEMP%\playtab_install.txt"
                del "%TEMP%\playtab_install.txt" >nul 2>nul
                pause
                exit /b 1
            )
        ) else (
            echo  ERROR: Installation failed.
            type "%TEMP%\playtab_install.txt"
            echo.
            echo  Troubleshooting:
            echo    - Check if the tablet has enough storage
            echo    - Try: adb uninstall %PKG%  then run this script again
            del "%TEMP%\playtab_install.txt" >nul 2>nul
            pause
            exit /b 1
        )
    )
    del "%TEMP%\playtab_install.txt" >nul 2>nul
) else (
    %ADB% install "%APK_PATH%" >nul 2>&1
    if %errorlevel% neq 0 (
        echo  ERROR: APK installation failed.
        pause
        exit /b 1
    )
)
echo  Installed successfully.

:: ---------------------------------------------------------------------------
:: Step 3: Set device owner
:: ---------------------------------------------------------------------------

echo.
echo  Step 3: Setting up device owner...

%ADB% shell dumpsys device_policy 2>nul | findstr /C:"%PKG%" >nul 2>nul
if %errorlevel% equ 0 (
    echo  PlayTab is already device owner. Skipping.
    goto :overlay
)

:: Check for user accounts
for /f %%i in ('%ADB% shell dumpsys account 2^>nul ^| find /c "Account {name="') do set ACCOUNT_COUNT=%%i
if !ACCOUNT_COUNT! gtr 0 (
    echo.
    echo  WARNING: The tablet has !ACCOUNT_COUNT! user account^(s^) that will
    echo  prevent device owner setup.
    echo.
    echo  Please remove all accounts now:
    echo    Settings ^> Accounts ^> Remove each account
    echo.
    echo  After removing accounts, press any key to continue.
    pause >nul
)

%ADB% shell dpm set-device-owner "%ADMIN_RECEIVER%" 2>"%TEMP%\playtab_setup_err.txt"
if %errorlevel% neq 0 (
    echo  ERROR: Could not set device owner.
    echo.
    type "%TEMP%\playtab_setup_err.txt"
    echo.
    echo  Common fixes:
    echo    - Remove ALL Google/user accounts from the tablet
    echo      ^(Settings ^> Accounts ^> Remove each account^)
    echo    - Make sure no other app is already set as device owner
    echo      Check: adb shell dumpsys device_policy
    echo    - On some tablets, you also need to remove the SIM card
    echo    - Factory reset the tablet if nothing else works
    echo.
    del "%TEMP%\playtab_setup_err.txt" >nul 2>nul
    pause
    exit /b 1
)
del "%TEMP%\playtab_setup_err.txt" >nul 2>nul
echo  Device owner set.

:: ---------------------------------------------------------------------------
:: Step 4: Grant overlay permission
:: ---------------------------------------------------------------------------

:overlay
echo.
echo  Step 4: Granting overlay permission...
%ADB% shell appops set %PKG% SYSTEM_ALERT_WINDOW allow
echo  Done.

:: ---------------------------------------------------------------------------
:: Step 5: Launch the app
:: ---------------------------------------------------------------------------

echo.
echo  Step 5: Launching PlayTab...
%ADB% shell am start -n %PKG%/.MainActivity >nul 2>nul

echo.
echo  ============================================
echo   SUCCESS! PlayTab v%LATEST% is ready.
echo  ============================================
echo.
echo  Next steps:
echo    1. PlayTab should now be open on the tablet
echo    2. Go to Admin Panel (PIN: 1234)
echo    3. Tap "Enable Kiosk Mode"
echo    4. Unplug USB -- you're done!
echo.
pause
