name: Docker

on:
  push:
    branches: [ "master" ]
    tags: [ 'v*.*.*' ]
  pull_request:
    branches: [ "master" ]
  workflow_dispatch:  # 允许手动触发

env:
  REGISTRY: registry.cn-hangzhou.aliyuncs.com  # 修改为你的阿里云镜像仓库地址
  IMAGE_NAME: jcce/pcm-core-api  # 修改为你的阿里云镜像仓库名称
  IMAGE_TAG: latest

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
      id-token: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.ALIYUN_USERNAME }}
          password: ${{ secrets.ALIYUN_PASSWORD }}

      - name: Get commit ID and build time
        id: get_tags
        run: |
          echo "::set-output name=build_time::$(date +'%Y%m%d%H%M%S')"

      - name: Build and push multi-arch image
        run: |
          docker buildx build \
            --platform linux/amd64,linux/arm64 \
            -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }} \
            -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.get_tags.outputs.build_time }} \
            --push .

      - name: Set up Kubernetes CLI
        uses: azure/setup-kubectl@v1

      - name: Configure kubeconfig
        run: |
          mkdir -p ~/.kube
          echo "${{ secrets.KUBECONFIG }}" > ~/.kube/config

      - name: Restart Deployment
        run: kubectl rollout restart deployment ${{ secrets.SSH_DEPLOYMENT }}