name: Deploy to K3s

on:
  push:
    branches:
      - master

jobs:
  deploy:
    container:
      image: localhost:5000/tiny-ci-runner:latest
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        run: |
          git clone --depth=1 --branch master \
            https://git.tonesc.cn/tone/tonePage.git \
            /workspace/tone/tonePage
          cd /workspace/tone/tonePage
          git log -1 --oneline

      - name: Build and push backend image
        run: |
          cd apps/backend
          docker build -t localhost:5000/backend:latest .
          docker push localhost:5000/backend:latest

      - name: Build and push frontend image
        run: |
          cd apps/frontend
          docker build \
            --build-arg API_BASE="http://backend-service:3001" \
            -t localhost:5000/frontend:latest .
          docker push localhost:5000/frontend:latest

      - name: Debug kubeconfig
        run: |
          echo "=== 1. Check if /root/.kube/config exists ==="
          ls -la /root/.kube/

          echo -e "\n=== 2. Show kubeconfig content (redacted) ==="
          cat /root/.kube/config | grep -v "certificate\|key"  # 隐藏敏感字段

          echo -e "\n=== 3. Check server address ==="
          grep "server:" /root/.kube/config

          echo -e "\n=== 4. Test kubectl cluster-info ==="
          kubectl cluster-info --kubeconfig=/root/.kube/config

          echo -e "\n=== 5. Test kubectl get nodes (quick API test) ==="
          kubectl get nodes --kubeconfig=/root/.kube/config

      - name: Deploy to K3s
        run: |
          cd apps/deploy
          kubectl apply -f postgres-deployment.yaml --kubeconfig=/root/.kube/config
          kubectl apply -f backend-deployment.yaml --kubeconfig=/root/.kube/config
          kubectl apply -f frontend-deployment.yaml --kubeconfig=/root/.kube/config
          kubectl rollout restart deployment/backend --kubeconfig=/root/.kube/config
          kubectl rollout restart deployment/frontend --kubeconfig=/root/.kube/config
          kubectl rollout status deployment/backend --timeout=120s --kubeconfig=/root/.kube/config
          kubectl rollout status deployment/frontend --timeout=120s --kubeconfig=/root/.kube/config
