name: build-and-push

on:
  push:
    branches: ["master", "main"]
    tags: ["v*"]
  workflow_dispatch:

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    env:
      REGISTRY: ${{ secrets.ACR_REGISTRY }}
      NAMESPACE: ${{ secrets.IMAGE_NAMESPACE }}
      ADMIN_IMAGE_NAME: zzyl-admin
      UI_IMAGE_NAME: zzyl-ui
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up JDK 11
        uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: "11"
          cache: maven

      - name: Build Jar
        run: mvn -B clean package -DskipTests

      - name: Prepare image tag
        shell: bash
        run: |
          if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then
            echo "IMAGE_TAG=${GITHUB_REF_NAME}" >> "$GITHUB_ENV"
          else
            echo "IMAGE_TAG=${GITHUB_SHA::7}" >> "$GITHUB_ENV"
          fi
          echo "ADMIN_IMAGE=${REGISTRY}/${NAMESPACE}/${ADMIN_IMAGE_NAME}" >> "$GITHUB_ENV"
          echo "UI_IMAGE=${REGISTRY}/${NAMESPACE}/${UI_IMAGE_NAME}" >> "$GITHUB_ENV"

      - name: Log in to Alibaba Cloud ACR
        uses: docker/login-action@v3
        with:
          registry: ${{ secrets.ACR_REGISTRY }}
          username: ${{ secrets.ACR_USERNAME }}
          password: ${{ secrets.ACR_PASSWORD }}

      - name: Build and push admin image
        uses: docker/build-push-action@v6
        with:
          context: zzyl-admin/target
          file: zzyl-admin/Dockerfile
          push: true
          tags: |
            ${{ env.ADMIN_IMAGE }}:${{ env.IMAGE_TAG }}

      - name: Build and push ui image
        uses: docker/build-push-action@v6
        with:
          context: zzyl-ui
          file: zzyl-ui/Dockerfile
          push: true
          tags: |
            ${{ env.UI_IMAGE }}:${{ env.IMAGE_TAG }}

      - name: Push admin latest tag on default branches
        if: github.ref_type == 'branch'
        uses: docker/build-push-action@v6
        with:
          context: zzyl-admin/target
          file: zzyl-admin/Dockerfile
          push: true
          tags: |
            ${{ env.ADMIN_IMAGE }}:latest

      - name: Push ui latest tag on default branches
        if: github.ref_type == 'branch'
        uses: docker/build-push-action@v6
        with:
          context: zzyl-ui
          file: zzyl-ui/Dockerfile
          push: true
          tags: |
            ${{ env.UI_IMAGE }}:latest
