name: Build and Deploy MkDocs

on:
  push:
    branches:
      - master  # Target branch.

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    steps:
    # 1) 正常检出代码
    - name: Checkout code
      uses: actions/checkout@v3

    # 2) 装 Python
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.9'

    # 3) 安装依赖
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements.txt

    # 4) 构建 MkDocs
    - name: Build MkDocs
      run: mkdocs build

    # 5) 显式配置 SSH 私钥 + known_hosts
    - name: Prepare SSH
      run: |
        mkdir -p ~/.ssh
        # 把 Secrets 中的私钥写入 id_rsa 并赋予 600 权限
        echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
        chmod 600 ~/.ssh/id_rsa

        # 启动 ssh-agent 并把 id_rsa 加载进去
        eval "$(ssh-agent -s)"
        ssh-add ~/.ssh/id_rsa

        # 将目标服务器添加到 known_hosts，避免初次连接询问
        ssh-keyscan -p ${{ secrets.SERVER_PORT || '22' }} ${{ secrets.SERVER_HOST }} >> ~/.ssh/known_hosts

    # 6) 通过 rsync 部署
    - name: Deploy to server
      run: |
        rsync -avz --delete site/ \
          --exclude='.user.ini' \
          --exclude='.htaccess' \
          ${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }}:/www/wwwroot/wiki/
