name: Backend Build and Push

on:
  push:
    tags:
      - "v[0-9]+.[0-9]+.[0-9]+*"

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        service: [api, consumer]
    timeout-minutes: 30

    outputs:
      version: ${{ steps.get_version.outputs.VERSION }}

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          lfs: true
          submodules: true
          token: ${{ secrets.PRO_TOKEN }}

      - name: Get version
        id: get_version
        run: |
          if [[ $GITHUB_REF == refs/tags/* ]]; then
            if [[ $GITHUB_REF == refs/tags/backend-* ]]; then
              echo "VERSION=${GITHUB_REF#refs/tags/backend-}" >> $GITHUB_OUTPUT
            else
              echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
            fi
          else
            echo "VERSION=${GITHUB_SHA::7}" >> $GITHUB_OUTPUT
          fi

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
        with:
          platforms: 'arm64,amd64'

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

      - name: Login to Aliyun Container Registry
        if: startsWith(github.ref, 'refs/tags/')
        uses: docker/login-action@v3
        with:
          registry: chaitin-registry.cn-hangzhou.cr.aliyuncs.com
          username: ${{ secrets.CT_ALIYUN_USER }}
          password: ${{ secrets.CT_ALIYUN_PASS }}

      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: ./backend
          file: ./backend/Dockerfile.${{ matrix.service }}.pro
          push: ${{ startsWith(github.ref, 'refs/tags/') }}
          platforms: linux/amd64, linux/arm64
          tags: chaitin-registry.cn-hangzhou.cr.aliyuncs.com/chaitin/panda-wiki-${{ matrix.service }}:${{ steps.get_version.outputs.VERSION }}
          build-args: |
            VERSION=${{ steps.get_version.outputs.VERSION }}
          cache-from: |
            type=gha,scope=${{ matrix.service }}
          cache-to: |
            type=gha,scope=${{ matrix.service }},mode=max
