name: Build PHP Flavours

on:
  push:
    paths:
      - 'php/apache/**'
      - 'php/cli/**'
      - 'php/nginx/**'
      - 'php/Dockerfile.Flavours'
  pull_request:
    branches:
      - '!dependabot/**'
  workflow_dispatch:
  workflow_run:
    workflows:
      - Build PHP Core
    branches: [ 'master', 'feature/**' ]
    types:
      - completed

jobs:
  php-flavours-build:
    name: "Build PHP Flavours"
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      max-parallel: 15
      matrix:
        variant:
          - cli
          - nginx
          - apache
        version:
          - "7.0"
          - "7.1"
          - "7.2"
          - "7.3"
          - "7.4"
          - "8.0"
          - "8.1"
          - "8.2"
          - "8.3"
    steps:
      - name: Mangle Envs
        id: vars
        run: |
          VERSION=$(echo "${{ matrix.version }}" | tr -d '.')
          PACKAGE_LIST=PHP_PACKAGES_$VERSION
          echo ::set-output name=php_packages::${!PACKAGE_LIST}

      - name: Show mangled envs
        run: |
          echo "Packages to be installed:"
          echo ${{ steps.vars.outputs.php_packages }}

      - uses: actions/github-script@v3
        name: Build Args
        id: build_args
        with:
          result-encoding: string
          script: return `PHP_VERSION=${{ matrix.version }}\nPHP_CORE_VERSION=benzine/php:core-${{ matrix.version }}`

      - uses: actions/checkout@v4
        with:
          sparse-checkout: php

      - uses: docker/setup-qemu-action@v2

      - uses: docker/setup-buildx-action@v2

      - name: "Setup: Login to Docker Hub"
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKER_HUB_USERNAME }}
          password: ${{ secrets.DOCKER_HUB_PASSWORD }}

      - name: "Setup: Login to GHCR"
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: ${{ secrets.GHCR_USERNAME }}
          password: ${{ secrets.GHCR_PASSWORD }}

      - uses: docker/build-push-action@v5
        name: "Build: Build & Push"
        with:
          context: php
          file: php/Dockerfile.Flavours
          target: php-${{ matrix.variant }}
          platforms: ${{ !env.ACT && 'linux/amd64,linux/arm64' || 'linux/amd64' }}
          pull: true
          push: ${{ !env.ACT && true || false }}
          tags: |
            ghcr.io/benzine-framework/php:${{ matrix.variant }}-${{ matrix.version }}
            gone/php:${{ matrix.variant }}-${{ matrix.version }}
            benzine/php:${{ matrix.variant }}-${{ matrix.version }}
          build-args: |
            ${{ steps.build_args.outputs.result }}
          cache-from: ${{ !env.ACT && 'type=gha' || 'type=local,src=.github/cache/docker' }}
          cache-to: ${{ !env.ACT && 'type=gha,mode=max' || 'type=local,dest=.github/cache/docker' }}