name: Publish Docker Images

on:
  push:
    tags:
      - "v*"
    branches:
      - main
    paths:
      - "api/**"
      - "client/**"
      - "docker/**"
      - "docker-compose*.yml"
      - ".github/workflows/dockerhub.yml"
  workflow_dispatch:

permissions:
  contents: read
  packages: write

jobs:
  push_to_registry:
    name: Push Docker images to Docker Hub
    runs-on: ubuntu-latest
    steps:
      - name: Get version info
        run: |
          if [[ $GITHUB_REF == refs/tags/* ]]; then
            echo "VERSION=${GITHUB_REF#refs/*/v}" >> $GITHUB_ENV
            echo "API_TAGS=${{secrets.DOCKER_API_REPO}}:latest,${{secrets.DOCKER_API_REPO}}:${GITHUB_REF#refs/*/v}" >> $GITHUB_ENV
            echo "UI_TAGS=${{secrets.DOCKER_UI_REPO}}:latest,${{secrets.DOCKER_UI_REPO}}:${GITHUB_REF#refs/*/v}" >> $GITHUB_ENV
          else
            echo "VERSION=dev" >> $GITHUB_ENV
            echo "API_TAGS=${{secrets.DOCKER_API_REPO}}:dev,${{secrets.DOCKER_API_REPO}}:dev-${GITHUB_SHA::7}" >> $GITHUB_ENV
            echo "UI_TAGS=${{secrets.DOCKER_UI_REPO}}:dev,${{secrets.DOCKER_UI_REPO}}:dev-${GITHUB_SHA::7}" >> $GITHUB_ENV
          fi

      - name: Check out the repo
        uses: actions/checkout@v3

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

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

      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_ACCESS_TOKEN }}

      - name: Build and push API image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: docker/Dockerfile.api
          platforms: linux/amd64,linux/arm64
          push: true
          build-args: |
            APP_ENV=${{ env.VERSION == 'dev' && 'local' || 'production' }}
            COMPOSER_FLAGS=${{ env.VERSION == 'dev' && '--optimize-autoloader --no-interaction' || '--no-dev --optimize-autoloader --no-interaction' }}
            APP_VERSION=${{ env.VERSION }}
          tags: ${{ env.API_TAGS }}
          cache-from: type=registry,ref=${{secrets.DOCKER_API_REPO}}:dev
          cache-to: type=inline

      - name: Build and push Client image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: docker/Dockerfile.client
          platforms: linux/amd64,linux/arm64
          push: true
          build-args: |
            APP_VERSION=${{ env.VERSION }}
          tags: ${{ env.UI_TAGS }}
          cache-from: type=registry,ref=${{secrets.DOCKER_UI_REPO}}:dev
          cache-to: type=inline
