@echo off
setlocal enabledelayedexpansion

echo ========================================
echo Mosis Device Installation Script
echo ========================================
echo.

:: Package name
set PACKAGE=com.omixlab.mosis
set DEVICE_APPS_DIR=files/apps

:: Step 1: Build and install APK
echo [1/3] Building and installing debug APK...
call gradlew installDebug
if errorlevel 1 (
    echo ERROR: Failed to install APK
    exit /b 1
)
echo.

:: Step 2: Push base-apps to temp location
echo [2/3] Pushing base-apps to temp location...
adb shell "rm -rf /data/local/tmp/mosis-apps" 2>nul
adb push base-apps /data/local/tmp/mosis-apps
if errorlevel 1 (
    echo ERROR: Failed to push base-apps
    exit /b 1
)
echo.

:: Step 3: Copy to private data using run-as
echo [3/3] Installing apps to internal storage...
echo   Using run-as for /data/data/%PACKAGE%/%DEVICE_APPS_DIR%/
echo.

:: Create apps directory
adb shell "run-as %PACKAGE% mkdir -p %DEVICE_APPS_DIR%"

:: List of apps to install
for /d %%A in (base-apps\com.mosis.*) do (
    set APP_ID=%%~nxA
    echo   Installing !APP_ID!...

    :: Create app directory structure
    adb shell "run-as %PACKAGE% mkdir -p %DEVICE_APPS_DIR%/!APP_ID!"

    :: Copy files using tar through run-as (faster than individual files)
    adb shell "cd /data/local/tmp/mosis-apps/!APP_ID! && tar cf - . | run-as %PACKAGE% tar xf - -C %DEVICE_APPS_DIR%/!APP_ID!/"
)

:: Cleanup temp files
echo.
echo Cleaning up temp files...
adb shell "rm -rf /data/local/tmp/mosis-apps"

echo.
echo ========================================
echo Installation complete!
echo ========================================
echo.
echo APK: %PACKAGE%
echo Apps: /data/data/%PACKAGE%/%DEVICE_APPS_DIR%/
echo.
echo Verify with:
echo   adb shell "run-as %PACKAGE% ls -la %DEVICE_APPS_DIR%"
echo.
echo Launch with:
echo   adb shell am start -n %PACKAGE%/.MainActivity
echo.
