@echo off
REM 自动化部署脚本 (Windows批处理版本)
REM 功能：更新mkdocs.yml -> Git提交推送 -> 服务器拉取并重启

setlocal enabledelayedexpansion

REM 配置参数
set "COMMIT_MESSAGE=%~1"
if "%COMMIT_MESSAGE%"=="" set "COMMIT_MESSAGE=更新文档"

set "SERVER_USER=renjianbo"
set "SERVER_HOST=101.43.95.130"
set "SERVER_PATH=%~4"
if "%SERVER_PATH%"=="" set "SERVER_PATH=~/devops/mkdocs"

echo =========================================
echo 步骤1: 更新mkdocs.yml
echo =========================================

python .\add_docs_to_mkdocs.py
if errorlevel 1 (
    echo [错误] 更新mkdocs.yml失败
    exit /b 1
)
echo [成功] mkdocs.yml更新成功

REM 检查是否有变更
echo.
echo 检查Git状态...
git status --porcelain >nul 2>&1
if errorlevel 1 (
    echo 没有文件变更，跳过Git操作
    exit /b 0
)

echo 发现以下变更:
git status --short

echo.
echo =========================================
echo 步骤2: Git提交和推送
echo =========================================

REM 添加所有变更
echo 添加文件到Git...
git add .
if errorlevel 1 (
    echo [错误] Git add 失败
    exit /b 1
)
echo [成功] 文件已添加到暂存区

REM 提交
echo 提交变更...
git commit -m "%COMMIT_MESSAGE%"
if errorlevel 1 (
    echo [错误] Git commit 失败
    exit /b 1
)
echo [成功] 变更已提交

REM 推送
echo 推送到远程仓库...
git push origin master
if errorlevel 1 (
    echo [错误] Git push 失败
    exit /b 1
)
echo [成功] 代码已推送到远程仓库

REM 步骤3: 服务器操作
if not "%SERVER_USER%"=="" if not "%SERVER_HOST%"=="" (
    echo.
    echo =========================================
    echo 步骤3: 服务器拉取代码并重启服务
    echo =========================================
    
    echo 连接到服务器: %SERVER_USER%@%SERVER_HOST%
    echo 执行命令: cd %SERVER_PATH% ^&^& git pull origin master ^&^& docker-compose restart
    
    ssh %SERVER_USER%@%SERVER_HOST% "cd %SERVER_PATH% && git pull origin master && docker-compose restart"
    if errorlevel 1 (
        echo [错误] 服务器操作失败
        echo [提示] 请确保已配置SSH密钥，或手动执行服务器命令
        exit /b 1
    )
    echo [成功] 服务器代码已更新，服务已重启
) else (
    echo.
    echo =========================================
    echo 步骤3: 服务器操作（跳过）
    echo =========================================
    echo 未配置服务器信息，跳过服务器操作
    echo.
    echo 使用方法:
    echo   deploy.bat [提交信息] [服务器用户] [服务器地址] [服务器路径]
    echo.
    echo 示例:
    echo   deploy.bat "更新文档" user example.com ~/devops/mkdocs
    echo.
    echo 或手动执行:
    echo   ssh user@host "cd ~/devops/mkdocs ^&^& git pull origin master ^&^& docker-compose restart"
)

echo.
echo =========================================
echo [成功] 部署完成！
echo =========================================

endlocal
