@echo off
setlocal enabledelayedexpansion
set cmdstr=rsync
set zipfile=cwrsync.zip
set downurl=https://itefix.net/download/free/cwrsync_6.3.0_x64_free.zip
set currpath=%~dp0
set "rsynchome=%ProgramFiles%\%zipfile:~0,-4%"
set passfile=%temp%\.password
set syncdir=dist/
:: 以下需要配置同步服务器
set accountwithost=kszny@47.96.93.140::mes2
set "password=kszny@123"
set "runcommand=%cmdstr% --port=873 -rlptvz --progress --password-file=%passfile% --exclude=google.exe --exclude=Lodap.zip %syncdir% %accountwithost%"

where %cmdstr% >nul 2>nul
::有错误输出,说明不存在该命令
if %errorlevel% neq 0 (
    ::还未下载安装包或未正常解压到安装目录
    if not exist "%rsynchome%" (
        :: 请求提升管理员权限
        echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\runAsAdmin.vbs"
        echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\runAsAdmin.vbs"
        "%temp%\runAsAdmin.vbs"
        :: 需要提升管理员权限才能创建此目录
        mkdir "%rsynchome%"
        del "%temp%\runAsAdmin.vbs"
        exit /B
    )

    :: 使用powershell的curl下载软件包
    powershell curl  -o %temp%\%zipfile% %downurl%
    :: 解压
    tar -xf "%temp%\%zipfile%" -C "%rsynchome%"
    echo "%cmdstr%已经安装到了%rsynchome%目录下"

    :: 检查路径是否存在于 PATH 中
    set "found=false"
    for %%I in ("%PATH:;=";"%") do (
        if /I "%%~I"=="%rsynchome%\bin" (
            set "found=true"
        )
    )

    :: 未设置到path变量中,添加到path变量
    if "!found!"=="false" (
        :: 更新注册表中的 PATH 变量,通过setx方式,变量值长度超过1024个字符就会被截断
        reg add "HKCU\Environment" /v PATH /t REG_EXPAND_SZ /d "%PATH%;%rsynchome%\bin" /f
    )

)

::当前目录下没有dist目录
if not exist "%currpath%%syncdir%" (
    echo 当前目录下没有需要同步的%syncdir%目录,请把需要同步的%syncdir%目录拷贝到当前目录下!
) else (
    echo !password!>%passfile%
    echo 数据同步开始,请稍后...
    !runcommand! && (
        echo 数据同步完成!
    ) || (
        echo !runcommand!
        echo 数据同步失败,请确认是否开启了VPN!
    )
    del %passfile%
)

endlocal
pause