name: Create and publish a Docker images

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

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push-image:
    name: PHP ${{ matrix.php-version }}, Fixer ${{ github.ref_name }}
    if: github.repository == 'PHP-CS-Fixer/PHP-CS-Fixer'
    runs-on: ubuntu-latest
    strategy:
      matrix:
        include:
          - php-version: '7.4'
            alpine-version: '3.16'
          - php-version: '8.0'
            alpine-version: '3.16'
          - php-version: '8.1'
            alpine-version: '3.18'
          - php-version: '8.2'
            alpine-version: '3.18'
          - php-version: '8.3'
            alpine-version: '3.18'

    permissions:
      contents: read
      packages: write

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

      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Make image lowercase
        run: |
          echo IMAGE_NAME_LOWER=$(echo ${{ env.IMAGE_NAME }} | tr '[:upper:]' '[:lower:]') >> ${GITHUB_ENV}

      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          flavor: |
            latest=false
            suffix=-php${{ matrix.php-version }}
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME_LOWER }}
          tags: |
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=semver,pattern={{major}}

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: Dockerfile
          target: dist
          build-args: |
            PHP_VERSION=${{ matrix.php-version }}
            ALPINE_VERSION=${{ matrix.alpine-version }}
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
