@echo off
setlocal EnableDelayedExpansion
REM Eazytec is pleased to support the open source community by making CPF-KMP-CMP available.
REM Copyright 2026 Eazytec. All rights reserved.
REM
REM Licensed under the Apache License, Version 2.0. See LICENSE for terms.
REM you may not use this file except in compliance with the License.
REM
REM Windows port of runOhosApp-Mac-auto.sh (all hdc targets x build modes).

pushd "%~dp0"
set "SCRIPT_DIR=%CD%"

set "DEFAULT_PLATFORM=ohosArm64"
set "DEFAULT_BUNDLE_NAME=com.example.harmonyapp"
set "DEFAULT_ABILITY_NAME=EntryAbility"
set "BUNDLE_NAME=%DEFAULT_BUNDLE_NAME%"
set "ABILITY_NAME=%DEFAULT_ABILITY_NAME%"
set "BUILD_MODE=debug"
set "BUILD_MODES_SELECT="
set "M_FLAG_SET=0"
set "DEBUG_MODE=attach"
set "LOCAL_OHOS_PATH="
set "PLATFORM="
set "SHOW_HELP=0"

REM bundle from harmonyApp AppScope app.json5 same as Mac grep bundleName
set "APP_JSON5=%SCRIPT_DIR%\harmonyApp\AppScope\app.json5"
if exist "%APP_JSON5%" (
  for /f "usebackq tokens=4 delims=^"" %%V in (`findstr /l /c:"bundleName" "%APP_JSON5%"`) do (
    set "_bv=%%V"
    set "_bv=!_bv:,=!"
    if not "!_bv!"=="" set "DEFAULT_BUNDLE_NAME=!_bv!" & set "BUNDLE_NAME=!_bv!"
  )
)

REM Parse options any position e.g. ohosArm64 -M release
:parse
if "%~1"=="" goto done_parse
if "%~1"=="-M" (set "BUILD_MODES_SELECT=%~2" & set "M_FLAG_SET=1" & shift & shift & goto parse)
if "%~1"=="-m" (set "BUILD_MODE=%~2" & shift & shift & goto parse)
if /i "%~1"=="-b" (set "BUNDLE_NAME=%~2" & shift & shift & goto parse)
if /i "%~1"=="-a" (set "ABILITY_NAME=%~2" & shift & shift & goto parse)
if /i "%~1"=="-d" (set "DEBUG_MODE=%~2" & shift & shift & goto parse)
if /i "%~1"=="-p" (set "LOCAL_OHOS_PATH=%~2" & shift & shift & goto parse)
if /i "%~1"=="-h" (set "SHOW_HELP=1" & shift & goto parse)
set "_A1=%~1"
if not "!_A1!"=="" if "!_A1:~0,1!"=="-" (
  echo Unknown option: !_A1!
  call :usage
  popd
  exit /b 1
)
if "!PLATFORM!"=="" set "PLATFORM=%~1"
shift
goto parse
:done_parse
if "!SHOW_HELP!"=="1" call :usage & popd & exit /b 0
if "!PLATFORM!"=="" set "PLATFORM=%DEFAULT_PLATFORM%"

if "!M_FLAG_SET!"=="0" call :prompt_build_modes_auto
if "!BUILD_MODES_SELECT!"=="" set "BUILD_MODES_SELECT=all"
set "HAS_DEBUG=0"
set "HAS_RELEASE=0"
if /i "!BUILD_MODES_SELECT!"=="debug" set "HAS_DEBUG=1"
if /i "!BUILD_MODES_SELECT!"=="release" set "HAS_RELEASE=1"
if /i "!BUILD_MODES_SELECT!"=="all" set "HAS_DEBUG=1" & set "HAS_RELEASE=1"
if "!HAS_DEBUG!!HAS_RELEASE!"=="00" set "HAS_DEBUG=1" & set "HAS_RELEASE=1"

call :get_epoch START_TIME

echo Run environment configuration:
echo   - Platform: %PLATFORM%
echo   - Devices: from hdc list targets ^(see below^)
echo   - Build modes: 由 -M 或菜单 1/2/3 ^(debug / release / debug+release^)
echo   - Debug mode: %DEBUG_MODE%
echo   - Bundle: %BUNDLE_NAME%
echo   - Ability: %ABILITY_NAME%
if not "!LOCAL_OHOS_PATH!"=="" echo   - External OHOS path: !LOCAL_OHOS_PATH!
echo ------------------------------------------------------------

if "!DEVECO_PATH!"=="" (
  if exist "C:\Program Files\Huawei\DevEco Studio" (
    set "DEVECO_PATH=C:\Program Files\Huawei\DevEco Studio"
  ) else if exist "D:\Program Files\Huawei\DevEco Studio" (
    set "DEVECO_PATH=D:\Program Files\Huawei\DevEco Studio"
  ) else (
    echo Error: DevEco Studio not found at default path. Set DEVECO_PATH.
    popd
    exit /b 1
  )
)
echo DevEco Studio Path: !DEVECO_PATH!
echo Checking environment configuration...

set "MIN_VERSION=6.0.0"
set "PRODUCT_INFO=!DEVECO_PATH!\product-info.json"
if exist "!PRODUCT_INFO!" (
  set "CURRENT_VERSION=unknown"
  for /f "usebackq tokens=4 delims=^"" %%v in (`findstr /c:"^"version^":" "!PRODUCT_INFO!"`) do (
    if "!CURRENT_VERSION!"=="unknown" (
      set "CURRENT_VERSION=%%v"
      set "CURRENT_VERSION=!CURRENT_VERSION:,=!"
    )
  )
) else (
  echo Warning: product-info.json not found, skipping version check.
  set "CURRENT_VERSION=unknown"
)

if not "!CURRENT_VERSION!"=="unknown" (
  echo Current DevEco version: !CURRENT_VERSION!
  echo Minimum required version: !MIN_VERSION!
  for /f "tokens=1,2 delims=." %%a in ("!CURRENT_VERSION!") do (set "CUR_MAJOR=%%a" & set "CUR_MINOR=%%b")
  for /f "tokens=1,2 delims=." %%a in ("!MIN_VERSION!") do (set "REQ_MAJOR=%%a" & set "REQ_MINOR=%%b")
  if !CUR_MAJOR! lss !REQ_MAJOR! (
    echo -------------------------------------------------------
    echo Error: DevEco version is too low!
    echo Current version: !CURRENT_VERSION!
    echo Minimum required: !MIN_VERSION!+
    echo Please upgrade DevEco Studio and run this script again.
    echo -------------------------------------------------------
    popd
    exit /b 5
  )
  if !CUR_MAJOR! equ !REQ_MAJOR! if !CUR_MINOR! lss !REQ_MINOR! (
    echo -------------------------------------------------------
    echo Error: DevEco version is too low!
    echo Current version: !CURRENT_VERSION!
    echo Minimum required: !MIN_VERSION!+
    echo Please upgrade DevEco Studio and run this script again.
    echo -------------------------------------------------------
    popd
    exit /b 5
  )
  echo DevEco version meets requirements ^(!CURRENT_VERSION!^)
)

set "HDC_BIN=!DEVECO_PATH!\sdk\default\openharmony\toolchains\hdc.exe"
set "DEVECO_SDK_HOME=!DEVECO_PATH!\sdk"
set "PATH=!DEVECO_PATH!\jbr\bin;!DEVECO_PATH!\tools\node;!DEVECO_PATH!\tools\ohpm\bin;!DEVECO_PATH!\tools\hvigor\bin;!DEVECO_SDK_HOME!;!PATH!"

if not exist "!HDC_BIN!" (
  echo Error: hdc not found at !HDC_BIN!
  popd
  exit /b 1
)

set "RUNOHOS_TMP=%TEMP%\runOhos_win_auto_%RANDOM%"
mkdir "%RUNOHOS_TMP%" 2>nul
set "DEV_FILE=%RUNOHOS_TMP%\devices.txt"
set "ERR_FILE=%RUNOHOS_TMP%\errors.txt"
set "PUSH_FILE=%RUNOHOS_TMP%\push.txt"
set "SIZE_FILE=%RUNOHOS_TMP%\sizes.txt"
del "%ERR_FILE%" "%PUSH_FILE%" "%SIZE_FILE%" 2>nul

del "%DEV_FILE%" 2>nul
for /f "tokens=1*" %%a in ('"!HDC_BIN!" list targets 2^>nul') do (
  if not "%%a"=="" echo %%a >>"%DEV_FILE%"
)
if not exist "%DEV_FILE%" (
  echo Error: No device found. Run 'hdc list targets' to check connected devices.
  popd
  exit /b 5
)
for %%F in ("%DEV_FILE%") do if %%~zF equ 0 (
  echo Error: No device found. Run 'hdc list targets' to check connected devices.
  popd
  exit /b 5
)

echo Devices:
type "%DEV_FILE%"
echo Build modes:
if "!HAS_DEBUG!"=="1" echo   debug
if "!HAS_RELEASE!"=="1" echo   release
echo ------------------------------------------------------------

set "TOTAL_COUNT=0"
set "SUCCESS_COUNT=0"

for /f "usebackq delims=" %%D in ("%DEV_FILE%") do (
  set "TID=%%D"
  set "TID=!TID: =!"
  if not "!TID!"=="" (
    set "TARGET_ID=!TID!"
    if "!HAS_DEBUG!"=="1" (set "BUILD_MODE=debug" & call :one_combo)
    if "!HAS_RELEASE!"=="1" (set "BUILD_MODE=release" & call :one_combo)
  )
)

call :get_epoch SCRIPT_END_TIME

echo.
echo ==============================================
echo 打包结果统计 / Packing Result Summary
echo ==============================================
echo   总次数 Total:     !TOTAL_COUNT!
echo   推包成功 Success: !SUCCESS_COUNT!
if !TOTAL_COUNT! gtr 0 (
  set /a RATE_PCT=!SUCCESS_COUNT!*100/!TOTAL_COUNT!
  echo   通过率 Rate:      !SUCCESS_COUNT!/!TOTAL_COUNT! = !RATE_PCT!%%
) else (
  echo   通过率 Rate:      N/A
)
set /a SCRIPT_ELAPSED=!SCRIPT_END_TIME!-!START_TIME!
echo   脚本总耗时:       !SCRIPT_ELAPSED!s
echo ==============================================

if exist "%ERR_FILE%" (
  echo.
  echo ----------------------------------------------
  echo 错误信息汇总
  echo ----------------------------------------------
  type "%ERR_FILE%"
  echo ----------------------------------------------
)
if exist "%PUSH_FILE%" (
  echo.
  echo ----------------------------------------------
  echo Push Time 汇总
  echo ----------------------------------------------
  type "%PUSH_FILE%"
  echo ----------------------------------------------
)
if exist "%SIZE_FILE%" (
  echo.
  echo ----------------------------------------------
  echo 包大小汇总
  echo ----------------------------------------------
  type "%SIZE_FILE%"
  echo ----------------------------------------------
)

rd /s /q "%RUNOHOS_TMP%" 2>nul
popd
if !SUCCESS_COUNT! lss !TOTAL_COUNT! exit /b 1
exit /b 0

:prompt_build_modes_auto
if /i "!RUNOHOS_NO_MENU!"=="1" (
  set "BUILD_MODES_SELECT=all"
  exit /b 0
)
echo.
echo 请选择打包类型（输入数字后回车）:
echo   1 = 仅 debug
echo   2 = 仅 release
echo   3 = debug + release（全部）
set "BMENU="
set /p "BMENU=请输入 1 / 2 / 3 [默认 3]: "
if "!BMENU!"=="" set "BMENU=3"
if "!BMENU!"=="1" set "BUILD_MODES_SELECT=debug" & exit /b 0
if "!BMENU!"=="2" set "BUILD_MODES_SELECT=release" & exit /b 0
if "!BMENU!"=="3" set "BUILD_MODES_SELECT=all" & exit /b 0
echo 无效输入，使用默认 3（debug+release）
set "BUILD_MODES_SELECT=all"
exit /b 0

:get_epoch
set "_epf=%TEMP%\ro_epoch_!RANDOM!.txt"
set "RO_EPOCH=!_epf!"
powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "$n=[int](Get-Date -UFormat '%%s'); $b=[Text.Encoding]::ASCII.GetBytes([string]$n); [IO.File]::WriteAllBytes($env:RO_EPOCH,$b)"
set "RO_EPOCH="
set "_epl="
for /f "usebackq delims=" %%L in ("!_epf!") do set "_epl=%%L"
del "!_epf!" 2>nul
set "%~1=!_epl!"
exit /b 0

:usage
echo Usage: %~nx0 ^[options^] ^[PLATFORM^]
echo.
echo Parameters:
echo   PLATFORM      Build platform ^(default: %DEFAULT_PLATFORM%^)
echo   Note            devices from hdc list targets, no TARGET_ID argument
echo.
echo Options:
echo   -M MODES      打包类型: debug ^| release ^| all ^(不传 -M 时提示输入 1/2/3；设 RUNOHOS_NO_MENU=1 则默认 all^)
echo   -m MODE       Build mode: debug or release ^(default: debug^)
echo   -b BUNDLE     Set bundle name ^(current: %DEFAULT_BUNDLE_NAME%^)
echo   -a ABILITY    Set Ability name ^(current: %DEFAULT_ABILITY_NAME%^)
echo   -d MODE       Debug mode: debug or attach ^(default: attach^)
echo   -p PATH       Set external OHOS project path ^(localOhosPath^)
echo   -h            Show this help message
echo.
echo Examples:
echo   %~nx0 ohosArm64
echo   %~nx0 -M debug
echo   %~nx0 -M release
echo   %~nx0 -M all
echo   %~nx0 -b com.test.app -a MainAbility
echo   %~nx0 -p D:\path\to\external\ohos\project
exit /b 0

:one_combo
set /a TOTAL_COUNT+=1
echo.
echo !TARGET_ID! 设备 !BUILD_MODE! 模式 进行打包
cd /d "!SCRIPT_DIR!"

set "ENTRY_BASE=!SCRIPT_DIR!\harmonyApp\entry"
set "CHECK_BASE=!SCRIPT_DIR!\harmonyApp"
set "HAP_PATH=!CHECK_BASE!\entry\build\default\outputs\default\entry-default-signed.hap"
set "LIBS_ARM=!CHECK_BASE!\entry\libs\arm64-v8a"
set "LIBS_X86=!CHECK_BASE!\entry\libs\x86_64"

set "DEL_RETRY=0"
:cleanup_loop
if exist "!ENTRY_BASE!\builds" rmdir /s /q "!ENTRY_BASE!\builds" 2>nul
if exist "!ENTRY_BASE!\build" rmdir /s /q "!ENTRY_BASE!\build" 2>nul
if exist "!ENTRY_BASE!\libs\" (
  for /r "!ENTRY_BASE!\libs" %%F in (*.so) do if exist "%%F" del /f /q "%%F" 2>nul
)
if exist "!ENTRY_BASE!\libs\arm64-v8a" rmdir /s /q "!ENTRY_BASE!\libs\arm64-v8a" 2>nul
if exist "!ENTRY_BASE!\libs\x86_64" rmdir /s /q "!ENTRY_BASE!\libs\x86_64" 2>nul
set "HAP_EXISTS=0"
if exist "!HAP_PATH!" set "HAP_EXISTS=1"
set "LIBS_EXISTS=0"
if exist "!LIBS_ARM!" set "LIBS_EXISTS=1"
if exist "!LIBS_X86!" set "LIBS_EXISTS=1"
if exist "!ENTRY_BASE!\libs\" (
  for /r "!ENTRY_BASE!\libs" %%F in (*.so) do (
    if exist "%%F" set "LIBS_EXISTS=1"
  )
)
if "!HAP_EXISTS!"=="0" if "!LIBS_EXISTS!"=="0" (
  echo 删除后检测: HAP包=无, libs中间产物=无，已确认清理完成
  goto cleanup_ok
)
set /a DEL_RETRY+=1
if !DEL_RETRY! geq 5 (
  echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：清理未完全，HAP包=!HAP_EXISTS!, libs中间产物=!LIBS_EXISTS!，须清光后再打包^)
  >>"%ERR_FILE%" echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：清理未完全^)
  cd /d "!SCRIPT_DIR!"
  exit /b 1
)
timeout /t 1 /nobreak >nul
goto cleanup_loop
:cleanup_ok

"!HDC_BIN!" -t !TARGET_ID! shell aa force-stop !BUNDLE_NAME! 2>nul

set "GRADLE_OUT=%RUNOHOS_TMP%\gradle_!RANDOM!.txt"
del "!GRADLE_OUT!" 2>nul

if "!PLATFORM!"=="ohosArm64" goto gradle_ohos
if "!PLATFORM!"=="ohosX86_64" goto gradle_ohos
if "!PLATFORM!"=="iosSimulatorArm64" (
  echo ^>^>^> :composeApp:linkDebugFrameworkIosSimulatorArm64
  call gradlew.bat :composeApp:linkDebugFrameworkIosSimulatorArm64 1>"!GRADLE_OUT!" 2>&1
  if errorlevel 1 (type "!GRADLE_OUT!" & goto gradle_fail)
  type "!GRADLE_OUT!"
  goto gradle_ok
)
echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：不支持的平台 !PLATFORM!^)
>>"%ERR_FILE%" echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：不支持的平台 !PLATFORM!^)
cd /d "!SCRIPT_DIR!"
exit /b 1

:gradle_ohos
if /i "!BUILD_MODE!"=="release" (
  echo ^>^>^> :composeApp:publishReleaseBinariesToHarmonyApp
  if not "!LOCAL_OHOS_PATH!"=="" (
    call gradlew.bat :composeApp:publishReleaseBinariesToHarmonyApp -PharmonyAppPath="!LOCAL_OHOS_PATH!" 1>"!GRADLE_OUT!" 2>&1
  ) else call gradlew.bat :composeApp:publishReleaseBinariesToHarmonyApp 1>"!GRADLE_OUT!" 2>&1
) else (
  echo ^>^>^> :composeApp:publishDebugBinariesToHarmonyApp
  if not "!LOCAL_OHOS_PATH!"=="" (
    call gradlew.bat :composeApp:publishDebugBinariesToHarmonyApp -PharmonyAppPath="!LOCAL_OHOS_PATH!" 1>"!GRADLE_OUT!" 2>&1
  ) else call gradlew.bat :composeApp:publishDebugBinariesToHarmonyApp 1>"!GRADLE_OUT!" 2>&1
)
if errorlevel 1 (type "!GRADLE_OUT!" & goto gradle_fail)
type "!GRADLE_OUT!"
goto gradle_ok

:gradle_fail
echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：Gradle publish 未成功^)
>>"%ERR_FILE%" echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：Gradle publish 未成功^)
echo   ^>^>^> 命令错误输出（含具体文件/配置报错^):
powershell -NoProfile -Command "Get-Content \"!GRADLE_OUT!\" -Tail 80"
del "!GRADLE_OUT!" 2>nul
cd /d "!SCRIPT_DIR!"
exit /b 1
:gradle_ok
del "!GRADLE_OUT!" 2>nul

call :get_epoch HAP_START_TIME

if not "!LOCAL_OHOS_PATH!"=="" (set "HARMONY_APP_DIR=!LOCAL_OHOS_PATH!") else (set "HARMONY_APP_DIR=!SCRIPT_DIR!\harmonyApp")
if not exist "!HARMONY_APP_DIR!" (
  echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：harmonyApp 目录不存在 !HARMONY_APP_DIR!^)
  >>"%ERR_FILE%" echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：harmonyApp 目录不存在^)
  cd /d "!SCRIPT_DIR!"
  exit /b 1
)
cd /d "!HARMONY_APP_DIR!"

set "HVIGOR_OUT=%RUNOHOS_TMP%\hvigor_!RANDOM!.txt"
call ohpm install --all 1>"!HVIGOR_OUT!" 2>&1
if errorlevel 1 (
  type "!HVIGOR_OUT!"
  echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：ohpm install 失败^)
  >>"%ERR_FILE%" echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：ohpm install 失败^)
  echo   ^>^>^> 命令错误输出:
  powershell -NoProfile -Command "Get-Content \"!HVIGOR_OUT!\" -Tail 80"
  del "!HVIGOR_OUT!" 2>nul
  cd /d "!SCRIPT_DIR!"
  exit /b 1
)
type "!HVIGOR_OUT!"
del "!HVIGOR_OUT!" 2>nul

call node "!DEVECO_PATH!\tools\hvigor\bin\hvigorw.js" --sync -p product=default -p buildMode=!BUILD_MODE! --analyze=normal --parallel --incremental --daemon 1>"!HVIGOR_OUT!" 2>&1
if errorlevel 1 (
  type "!HVIGOR_OUT!"
  echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：hvigor --sync 失败，请查看下方输出中的文件/配置名^)
  >>"%ERR_FILE%" echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：hvigor --sync 失败^)
  echo   ^>^>^> 命令错误输出:
  powershell -NoProfile -Command "Get-Content \"!HVIGOR_OUT!\" -Tail 80"
  del "!HVIGOR_OUT!" 2>nul
  cd /d "!SCRIPT_DIR!"
  exit /b 1
)
type "!HVIGOR_OUT!"
del "!HVIGOR_OUT!" 2>nul

if /i "!BUILD_MODE!"=="release" (
  call node "!DEVECO_PATH!\tools\hvigor\bin\hvigorw.js" --mode module -p module=entry -p product=default -p buildMode=release -p requiredDeviceType=phone assembleHap compileNative --analyze=normal --parallel --incremental --daemon 1>"!HVIGOR_OUT!" 2>&1
) else (
  call node "!DEVECO_PATH!\tools\hvigor\bin\hvigorw.js" --mode module -p module=entry@default -p product=default -p buildMode=debug -p requiredDeviceType=phone assembleHap --analyze=normal --parallel --incremental --daemon 1>"!HVIGOR_OUT!" 2>&1
)
if errorlevel 1 (
  type "!HVIGOR_OUT!"
  echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：hvigor assembleHap 失败，请查看下方输出中的文件/配置名^)
  >>"%ERR_FILE%" echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：hvigor assembleHap 失败^)
  echo   ^>^>^> 命令错误输出:
  powershell -NoProfile -Command "Get-Content \"!HVIGOR_OUT!\" -Tail 80"
  del "!HVIGOR_OUT!" 2>nul
  cd /d "!SCRIPT_DIR!"
  exit /b 1
)
type "!HVIGOR_OUT!"
del "!HVIGOR_OUT!" 2>nul

set "SIGNED_HAP=entry-default-signed.hap"
set "HAP_FILE=entry\build\default\outputs\default\!SIGNED_HAP!"
if not exist "!HAP_FILE!" (
  echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：未找到已签名 HAP 包 !HAP_FILE!^)
  >>"%ERR_FILE%" echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：未找到已签名 HAP 包^)
  cd /d "!SCRIPT_DIR!"
  exit /b 1
)

set "LIST_OUT=%RUNOHOS_TMP%\list_!RANDOM!.txt"
"!HDC_BIN!" list targets 1>"!LIST_OUT!" 2>nul
findstr /c:"!TARGET_ID!" "!LIST_OUT!" >nul
if errorlevel 1 (
  echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：设备离线或未连接^)
  >>"%ERR_FILE%" echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：设备离线或未连接^)
  del "!LIST_OUT!" 2>nul
  cd /d "!SCRIPT_DIR!"
  exit /b 1
)
del "!LIST_OUT!" 2>nul

set "HAP_FILE_ABS=!CD!\entry\build\default\outputs\default\!SIGNED_HAP!"
set "REMOTE_HAP_DIR=/data/local/tmp/debug_install"
set "REMOTE_HAP_PATH=!REMOTE_HAP_DIR!/!SIGNED_HAP!"

"!HDC_BIN!" -t !TARGET_ID! shell bm uninstall -n !BUNDLE_NAME! 2>nul
"!HDC_BIN!" -t !TARGET_ID! shell mkdir -p !REMOTE_HAP_DIR!
"!HDC_BIN!" -t !TARGET_ID! file send "!HAP_FILE_ABS!" !REMOTE_HAP_DIR!

set "INST_OUT=%RUNOHOS_TMP%\inst_!RANDOM!.txt"
"!HDC_BIN!" -t !TARGET_ID! shell bm install -p "!REMOTE_HAP_PATH!" 1>"!INST_OUT!" 2>&1
type "!INST_OUT!"
timeout /t 1 /nobreak >nul
findstr /i /c:"failed" /c:"error" "!INST_OUT!" >nul
if not errorlevel 1 (
  "!HDC_BIN!" -t !TARGET_ID! shell bm uninstall -n !BUNDLE_NAME! 2>nul
  timeout /t 5 /nobreak >nul
  "!HDC_BIN!" -t !TARGET_ID! shell bm install -p "!REMOTE_HAP_PATH!" 1>"!INST_OUT!" 2>&1
  type "!INST_OUT!"
  timeout /t 5 /nobreak >nul
)
findstr /i /c:"failed" /c:"error" "!INST_OUT!" >nul
if not errorlevel 1 (
  echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：安装失败 bm install^)
  >>"%ERR_FILE%" echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：安装失败 bm install^)
  type "!INST_OUT!"
  del "!INST_OUT!" 2>nul
  cd /d "!SCRIPT_DIR!"
  exit /b 1
)
del "!INST_OUT!" 2>nul

"!HDC_BIN!" -t !TARGET_ID! shell rm -rf !REMOTE_HAP_DIR! 2>nul
timeout /t 1 /nobreak >nul

if /i "!DEBUG_MODE!"=="debug" (
  "!HDC_BIN!" -t !TARGET_ID! shell aa start -a !ABILITY_NAME! -b !BUNDLE_NAME! -D 1>"%RUNOHOS_TMP%\aa.txt" 2>&1
) else (
  "!HDC_BIN!" -t !TARGET_ID! shell aa start -a !ABILITY_NAME! -b !BUNDLE_NAME! 1>"%RUNOHOS_TMP%\aa.txt" 2>&1
)
type "%RUNOHOS_TMP%\aa.txt"

call :get_epoch END_TIME

findstr /i /c:"10106102" /c:"screen is locked" "%RUNOHOS_TMP%\aa.txt" >nul
if not errorlevel 1 (
  echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：设备屏幕已锁定，请解锁后重试^)
  >>"%ERR_FILE%" echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：设备屏幕已锁定^)
  cd /d "!SCRIPT_DIR!"
  exit /b 1
)

set /a COUNT=0
:wait_pid
set "APP_PID="
for /f "tokens=1" %%i in ('"!HDC_BIN!" -t !TARGET_ID! shell pidof !BUNDLE_NAME! 2^>nul') do set "APP_PID=%%i"
if not "!APP_PID!"=="" goto got_pid
timeout /t 1 /nobreak >nul
set /a COUNT+=1
if !COUNT! lss 45 goto wait_pid
echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：应用在 45s 内未启动，请检查设备与安装结果^)
>>"%ERR_FILE%" echo 错误的 !TARGET_ID! 设备 !BUILD_MODE! 模式（原因：应用未启动^)
echo   ^>^>^> aa start 输出见上方 type 日志
cd /d "!SCRIPT_DIR!"
exit /b 1
:got_pid

set /a ELAPSED_SO=!HAP_START_TIME!-!START_TIME!
set /a M=!ELAPSED_SO!/60
set /a S=!ELAPSED_SO!%%60
set /a ELAPSED_HAP=!END_TIME!-!HAP_START_TIME!
set /a M2=!ELAPSED_HAP!/60
set /a S2=!ELAPSED_HAP!%%60
set /a ELAPSED_TOT=!END_TIME!-!START_TIME!
set /a M3=!ELAPSED_TOT!/60
set /a S3=!ELAPSED_TOT!%%60
echo   - SO build time: !M!m!S!s ^(!ELAPSED_SO!s^)
echo   - HAP package and push time: !M2!m!S2!s ^(!ELAPSED_HAP!s^)
echo   - Total time: !M3!m!S3!s ^(!ELAPSED_TOT!s^)

set "HAP_BYTES="
if exist "!HAP_FILE_ABS!" for %%Z in ("!HAP_FILE_ABS!") do set "HAP_BYTES=%%~zZ"
if defined HAP_BYTES if !HAP_BYTES! gtr 0 (
  set "SIZE_STR=!HAP_BYTES! B"
  if !HAP_BYTES! geq 1048576 (set /a MB=!HAP_BYTES!/1048576 & set "SIZE_STR=!MB! MB ^(!HAP_BYTES! B^)") else if !HAP_BYTES! geq 1024 (set /a KB=!HAP_BYTES!/1024 & set "SIZE_STR=!KB! KB ^(!HAP_BYTES! B^)")
  echo   - HAP 包大小: !SIZE_STR!
  >>"%SIZE_FILE%" echo   !TARGET_ID! ^| !BUILD_MODE! ^| !SIZE_STR!
)
>>"%PUSH_FILE%" echo   !TARGET_ID! ^| !BUILD_MODE! ^| SO:!ELAPSED_SO!s HAP+push:!ELAPSED_HAP!s 总:!ELAPSED_TOT!s

echo !TARGET_ID! 设备 !BUILD_MODE! 模式 打包成功
set /a SUCCESS_COUNT+=1
cd /d "!SCRIPT_DIR!"
exit /b 0
