@echo off
setlocal enabledelayedexpansion

REM 获取当前批处理文件所在目录
set "CURRENT_DIR=%~dp0"
set "CURRENT_DIR=%CURRENT_DIR:~0,-1%"

echo 当前路径: %CURRENT_DIR%
echo.
echo 配置 Syncthing 服务...
echo.

REM 检查服务是否存在
sc query Syncthing >nul 2>&1
if %errorlevel% equ 0 goto delete_service
goto add_service

:delete_service
echo 检测到已存在的服务，正在删除...
sc stop Syncthing >nul 2>&1
timeout /t 3 >nul
sc delete Syncthing
echo 等待服务完全删除...
timeout /t 8 >nul
goto add_service

:add_service
echo 添加 Syncthing 服务...
"%CURRENT_DIR%\shawl.exe" add --name Syncthing --restart -- "%CURRENT_DIR%\syncthing.exe" --home="%CURRENT_DIR%\synctingData"
if %errorlevel% neq 0 goto add_failed
goto configure_service

:add_failed
echo.
echo 服务添加失败！
echo 提示：如果提示服务已标记删除，请重启计算机后重试
pause
exit /b 1

:configure_service
echo 设置开机自动启动...
sc config Syncthing start= auto

echo 设置网络依赖...
sc config Syncthing depend= Tcpip

echo 设置失败恢复策略（15秒延迟）...
sc failure Syncthing reset= 86400 actions= restart/15000/restart/15000/restart/15000

echo 设置服务描述...
sc description Syncthing "Syncthing - 开源文件同步服务"

echo.
echo 启动服务...
sc start Syncthing
if %errorlevel% neq 0 goto start_failed
goto success

:start_failed
echo.
echo 服务启动失败，请检查日志
goto show_status

:success
echo.
echo ========================================
echo 配置完成！
echo 路径: %CURRENT_DIR%
echo 失败重启延迟: 15秒
echo 开机启动: 已启用
echo 网络依赖: Tcpip（TCP/IP协议栈）
echo ========================================

:show_status
echo.
echo 按任意键查看服务状态...
pause

echo.
echo ====== 服务状态 ======
sc query Syncthing
echo.
echo ====== 服务配置 ======
sc qc Syncthing
echo.
echo ====== 失败恢复配置 ======
sc qfailure Syncthing

pause