name: Build Swarm Loadbalancer

permissions:
  contents: read
  packages: write

on:
  workflow_call:
  workflow_dispatch:

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

env:
  PLATFORMS: linux/amd64,linux/arm64
  CANDIDATE_IMAGE: ghcr.io/benzine-framework/bouncer:build-${{ github.sha }}

jobs:
  build:
    name: Build Swarm Loadbalancer
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - id: date
        run: |
          {
            echo "datetime=$(date +'%Y-%m-%d %H:%M:%S')"
            echo "date=$(date +'%Y-%m-%d')"
            echo "time=$(date +'%H:%M:%S')"
            echo "container_build_datetime=$(date -u +'%Y-%m-%dT%H:%M:%S.%3NZ')"
          } >> "$GITHUB_OUTPUT"
      - id: read-php-version
        run: echo "php_version=$(jq -r '.require["php"]' composer.json | sed -E 's/[^0-9.]//g')" >> $GITHUB_OUTPUT
      - uses: shivammathur/setup-php@v2
        with:
          php-version: ${{ steps.read-php-version.outputs.php_version }}
      - uses: docker/setup-qemu-action@v3
      - uses: crazy-max/ghaction-github-runtime@v3
      - uses: docker/setup-buildx-action@v3
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: matthewbaggett
          password: ${{ secrets.GITHUB_TOKEN }}
      - id: composer-cache-find
        run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT
      - id: composer-cache
        uses: actions/cache@v4
        with:
          path: ${{ steps.composer-cache.outputs.dir }}
          key: "${{ runner.os }}-bouncer-composer-${{ hashFiles('**/composer.lock') }}"
          restore-keys: ${{ runner.os }}-bouncer-composer-
      - run: composer install --ignore-platform-reqs
      - name: "Build & Push Candidate Image as ${{ env.CANDIDATE_IMAGE }}"
        uses: docker/build-push-action@v5
        with:
          context: .
          target: bouncer
          build-contexts: |
            php:cli=docker-image://ghcr.io/benzine-framework/php:cli-${{ steps.read-php-version.outputs.php_version }}
          build-args: |
            GIT_SHA=${{ github.sha }}
            GIT_BUILD_ID=${{ github.ref_name }}
            BUILD_DATE=${{ steps.date.outputs.container_build_datetime }}
            GIT_COMMIT_MESSAGE=${{ github.event.head_commit.message }}
          platforms: ${{ !env.ACT && env.PLATFORMS || 'linux/amd64' }}
          pull: true
          push: true
          tags: ${{ env.CANDIDATE_IMAGE }}
          cache-from: ${{ !env.ACT && 'type=gha' || '' }}
          cache-to: ${{ !env.ACT && 'type=gha,mode=max' || '' }}