@echo off
cd /d "%~dp0"
set "ADB=adb"
if exist "%~dp0adb.exe" set "ADB=%~dp0adb.exe"

set "SERIAL=%~1"
if "%SERIAL%"=="" (
  for /f "skip=1 tokens=1,2" %%a in ('"%ADB%" devices 2^>nul') do (
    if "%%b"=="device" if not defined SERIAL set "SERIAL=%%a"
  )
)
if not defined SERIAL (
  echo Usage: oneplus8t-incremental-push.bat [192.168.x.x:port]
  pause
  exit /b 1
)

if not exist "libcameraservice.so" (
  echo Download first:
  echo   system/lib64/libcameraservice.so -^> libcameraservice.so
  echo   system/bin/cameraserver
  echo   incremental-external_camera_config.xml
  pause
  exit /b 1
)

echo Device: %SERIAL%
echo.
"%ADB%" -s "%SERIAL%" root
timeout /t 2 /nobreak >nul
"%ADB%" -s "%SERIAL%" remount
if errorlevel 1 (
  echo remount failed. Enable Root access Apps+ADB in Developer options.
  pause
  exit /b 1
)

echo Push libcameraservice + cameraserver...
"%ADB%" -s "%SERIAL%" push libcameraservice.so /system/lib64/libcameraservice.so
"%ADB%" -s "%SERIAL%" push cameraserver /system/bin/cameraserver
if exist "incremental-external_camera_config.xml" (
  echo Push external_camera_config.xml...
  "%ADB%" -s "%SERIAL%" push incremental-external_camera_config.xml /vendor/etc/external_camera_config.xml
  "%ADB%" -s "%SERIAL%" shell chmod 644 /vendor/etc/external_camera_config.xml
  "%ADB%" -s "%SERIAL%" shell stop vendor.camera-provider-2-7-ext
  "%ADB%" -s "%SERIAL%" shell start vendor.camera-provider-2-7-ext
)

"%ADB%" -s "%SERIAL%" shell chmod 644 /system/lib64/libcameraservice.so
"%ADB%" -s "%SERIAL%" shell chmod 755 /system/bin/cameraserver
echo.
echo Rebooting...
"%ADB%" -s "%SERIAL%" reboot
echo Done. After boot: plug UVC, uvc-replace-role back, test back camera.
pause
