@echo off
chcp 65001 >nul
setlocal EnableDelayedExpansion

:: 检查是否以管理员身份运行
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo ========================================
    echo Error: This script requires administrator privileges
    echo ========================================
    echo.
    echo Please right-click and select "Run as administrator"
    pause
    exit /b 1
)

echo ========================================
echo Add ADB to System PATH
echo ========================================
echo.

set ADB_PATH=C:\Users\GIGABYTE\AppData\Local\Android\Sdk\platform-tools

:: 检查 ADB 路径是否存在
if not exist "%ADB_PATH%" (
    echo Error: ADB path does not exist: %ADB_PATH%
    echo.
    pause
    exit /b 1
)

echo ADB Path: %ADB_PATH%
echo.

:: 获取当前系统 PATH
for /f "tokens=2*" %%A in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH 2^>nul') do set "CURRENT_PATH=%%B"

:: 检查 PATH 中是否已包含 ADB 路径
echo %CURRENT_PATH% | findstr /C:"%ADB_PATH%" >nul
if %errorLevel% equ 0 (
    echo ADB path is already in system PATH
    echo.
    echo Current PATH contains: %ADB_PATH%
    echo.
    pause
    exit /b 0
)

echo Adding ADB path to system PATH...
echo.

:: 添加 ADB 路径到系统 PATH
setx PATH "%CURRENT_PATH%;%ADB_PATH%" /M >nul 2>&1
if %errorLevel% neq 0 (
    echo Error: Failed to add ADB path to system PATH
    echo.
    echo Trying alternative method...
    
    :: 使用 reg 命令直接修改注册表
    reg add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH /t REG_EXPAND_SZ /d "%CURRENT_PATH%;%ADB_PATH%" /f >nul 2>&1
    if %errorLevel% neq 0 (
        echo Error: Failed to modify system PATH
        pause
        exit /b 1
    )
    
    :: 广播环境变量更改
    call :BroadcastEnvironmentChange
    echo Success: ADB path added to system PATH (using registry method)
) else (
    echo Success: ADB path added to system PATH
)

echo.
echo ========================================
echo Important Notes:
echo ========================================
echo 1. You may need to restart your command prompt
echo 2. Or restart your computer for changes to take effect
echo 3. To verify, open a new command prompt and run: adb version
echo.
echo ========================================
echo Verification
echo ========================================
echo.
echo Testing ADB command...
"%ADB_PATH%\adb.exe" version >nul 2>&1
if %errorLevel% equ 0 (
    echo ADB is working correctly at: %ADB_PATH%
) else (
    echo Warning: ADB command test failed
    echo Please verify the path is correct
)
echo.
pause
exit /b 0

:BroadcastEnvironmentChange
:: 广播环境变量更改消息
set "HWND_BROADCAST=0xFFFF"
set "WM_SETTINGCHANGE=0x001A"
powershell -Command "[System.Environment]::SetEnvironmentVariable('PATH', [System.Environment]::GetEnvironmentVariable('PATH', 'Machine'), 'Machine')" >nul 2>&1
exit /b

