name: Build S3DB

on:
  workflow_call:
  workflow_dispatch:
  workflow_run:
    workflows: ["Postgres", "MariaDB"]
    types: [completed]

  push:
    branches:
      - main
    paths:
      - s3db/**
      - .github/workflows/s3db.yml

concurrency:
  group: ${{ github.workflow }}-s3db-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true

jobs:
  s3db-build:
    name: Build S3DB
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        database:
          - postgres
          - mariadb
        include:
          - database: postgres
            version: 16
          - database: postgres
            version: 15
          - database: mariadb
            version: 11
          - database: mariadb
            version: 10

    steps:
      - name: "Setup: PHP"
        uses: shivammathur/setup-php@v2
        with:
          php-version: 8.1
        env:
          runner: self-hosted

      - name: "Setup: Setup QEMU"
        uses: docker/setup-qemu-action@v3

      - name: "Setup: Expose GitHub Runtime"
        uses: crazy-max/ghaction-github-runtime@v3

      - name: "Setup: Setup Docker Buildx"
        uses: docker/setup-buildx-action@v2

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

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

      - name: "Setup: Checkout Source"
        uses: actions/checkout@v4
        with:
          sparse-checkout: |
            s3db

      - name: "Setup: Configure Cache"
        uses: actions/cache@v4
        with:
          path: s3db
          key: ${{ runner.os }}-s3db-composer-${{ hashFiles('**/composer.lock') }}
          restore-keys: |
            ${{ runner.os }}-s3db-composer-

      - name: "Dependencies: Composer Install"
        working-directory: s3db
        run: composer install --ignore-platform-reqs

      - name: "Build: Build & Push Image"
        uses: docker/build-push-action@v5
        with:
          context: s3db
          target: ${{ matrix.database }}
          file: s3db/Dockerfile.${{ matrix.database }}
          platforms: ${{ !env.ACT && 'linux/amd64,linux/arm64' || 'linux/amd64' }}
          push: true
          tags: |
            ghcr.io/benzine-framework/s3db:${{ matrix.database }}-${{ matrix.version }}
            benzine/s3db:${{ matrix.database }}-${{ matrix.version }}
          cache-from: ${{ !env.ACT && 'type=gha' || '' }}
          cache-to: ${{ !env.ACT && 'type=gha,mode=max' || '' }}
          build-contexts: |
            postgres:injected-version=docker-image://ghcr.io/benzine-framework/postgres:${{ matrix.version }}-alpine
            mariadb:injected-version=docker-image://ghcr.io/benzine-framework/mariadb:${{ matrix.version }}