# This workflow builds and pushes a multi-architecture Docker image to GitHub Container Registry (ghcr.io).
#
# The Docker meta step is required because GitHub repository names can contain uppercase letters, but Docker image tags must be lowercase.
# The docker/metadata-action@v5 normalizes the repository name to lowercase, ensuring the build and push steps use a valid image tag.
#
# This workflow builds for both AMD64 and ARM64 architectures using Docker Buildx and QEMU emulation.

name: Build and Push Docker image

on:
  push:
    branches:
      - main
      - '*'  # This will run the workflow on any branch
  workflow_dispatch:  # This enables manual triggering

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    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: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Docker meta
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ghcr.io/${{ github.repository }}

      - name: Set normalized image name
        run: |
          if [[ "${{ github.ref_name }}" == "main" ]]; then
            echo "IMAGE_NAME=$(echo ${{ steps.meta.outputs.tags }} | sed 's/:main/:latest/')" >> $GITHUB_ENV
          else
            echo "IMAGE_NAME=${{ steps.meta.outputs.tags }}" >> $GITHUB_ENV
          fi

      - name: Build and push multi-architecture Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./docker/Dockerfile
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ env.IMAGE_NAME }}