name: Docker Build and Push
on:
  push:
    tags:
      - 'release/*'  # 匹配所有release开头的标签，如release/v0.1.6

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    steps:
      - run: echo "🎉 该作业由 ${{ gitea.event_name }} 事件自动触发。"
      - run: echo "🐧 此作业当前在 Gitea 托管的 ${{ runner.os }} 服务器上运行！"
      - run: echo "🔎 您的标签名称是 ${{ gitea.ref_name }}，仓库是 ${{ gitea.repository }}。"
      - name: 检出仓库代码
        uses: actions/checkout@v4
      - run: echo "💡 ${{ gitea.repository }} 仓库已克隆到运行器。"
      - run: echo "🖥️ 工作流现在已准备好在运行器上测试您的代码。"
      - name: 列出仓库中的文件
        run: |
          ls ${{ gitea.workspace }}
      - run: echo "🍏 此作业的状态是 ${{ job.status }}。"

      - name: 设置 Docker Buildx
        uses: docker/setup-buildx-action@v3
      
      - name: 从标签名中提取版本号
        id: extract_version
        run: |
          # 从标签名中提取版本号，例如从 release/v0.1.6 中提取 v0.1.6
          VERSION=$(echo "${{ gitea.ref_name }}" | sed 's|release/||')
          echo "VERSION=$VERSION" >> $GITHUB_ENV
          echo "提取的版本号：$VERSION"
      
      - name: 登录 Docker 注册表
        uses: docker/login-action@v3
        with:
          registry: registry.cn-beijing.aliyuncs.com
          username: ${{ secrets.ALI_DOCKER_REGISTRY_USERNAME }}
          password: ${{ secrets.ALI_DOCKER_REGISTRY_PASSWORD }}

      - name: 构建并推送
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          push: true
          tags: |
            registry.cn-beijing.aliyuncs.com/d8dcloud/d8d-ai-design-prd:release-${{ env.VERSION }}
      - name: 更新服务器上的 Docker 容器 
        uses: appleboy/ssh-action@v1.2.2
        with:
          host: ${{ secrets.SERVER_HOST }}
          port: ${{ secrets.SERVER_PORT }}
          username: ${{ secrets.SERVER_USER }}
          key: ${{ secrets.SERVER_SSH_KEY }}
          script: |
            # 进入项目目录
            cd /mnt/k8s_home/app/d8d-fun-vite

            
            # 备份当前的 deployment.yaml 文件
            cp deployment.yaml deployment.yaml.bak
            
            # 更新 deployment.yaml 中的镜像版本
            sed -i "s|registry.cn-beijing.aliyuncs.com/d8dcloud/d8d-ai-design-prd:.*|registry.cn-beijing.aliyuncs.com/d8dcloud/d8d-ai-design-prd:release-${{ env.VERSION }}|g" deployment.yaml
            
            # 检查文件是否成功更新
            echo "更新后的 deployment.yaml 内容："
            cat deployment.yaml
            
            # 更新
            kubectl apply -f deployment.yaml
            
            # 显示d8d-fun-vite pod状态
            kubectl get pods -n default -l app=d8d-fun-vite