name: Build and Push Next.js to Private Registry

on:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    steps:
      # 替换 actions/checkout@v4：直接利用 Runner 容器自带的 git 命令克隆
      # Gitea 会自动注入环境变量 $GITEA_SERVER_URL, $GITEA_REPOSITORY, $GITEA_SHA
      - name: 检查代码 (本地原生 Git)
        run: |
          git clone ${{ github.server_url }}/${{ github.repository }}.git .
          git checkout ${{ github.sha }}

      - name: 生成短哈希版本号
        id: vars
        run: echo "sha_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT

      - name: 构建并推送镜像 (本地 Docker)
        run: |
          IMAGE_NAME="192.168.10.236:31051/nextjs-app"
          SHA_TAG="${{ steps.vars.outputs.sha_short }}"
          docker build -t ${IMAGE_NAME}:latest -t ${IMAGE_NAME}:${SHA_TAG} -f ./Dockerfile .
          docker push ${IMAGE_NAME}:latest
          docker push ${IMAGE_NAME}:${SHA_TAG}

            # 核心解决步骤：通过 SSH 穿透容器，在宿主机本地执行 kubectl
      - name: 穿透容器：在宿主机本地触发 K3s 灰度发布
        uses: osc-org/appleboy-ssh-action@main
        with:
          host: 192.168.10.236
          username: root
          key: clkj123
          script: |
            # 此时以下命令全部在宿主机物理机上直接运行，绝不会报 command not found
            SHA_TAG="${{ steps.vars.outputs.sha_short }}"
            
            echo "1. 正在应用物理机 /home/ 目录下的基础设施配置..."
            kubectl apply -f /home/ai/k3s/nextjs-traefik-gray.yaml
            
            echo "2. 正在更新 K3s 灰度版本镜像至: ${SHA_TAG}"
            kubectl set image deployment/nextjs-app-canary nextjs=192.168.10.236:31051/nextjs-app:${SHA_TAG}
            
            echo "3. 等待灰度 Pod 滚动更新完成..."
            kubectl rollout status deployment/nextjs-app-canary --timeout=60s
            
            echo "【发布成功】新标签 [${SHA_TAG}] 已就绪，已切入 Traefik Header [version: canary] 路由！"
      