name: Build
on:
  pull_request:
  push:
    branches:
      - main

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

jobs:
  detect:
    permissions:
      contents: read
    runs-on: ubuntu-latest
    outputs:
      flavor: ${{ steps.set-matrix.outputs.flavor }}
      platform: ${{ steps.set-platform.outputs.platform }}
    steps:
    - id: set-matrix
      run: |
        echo "flavor=['green', 'blue', 'orange']" >> $GITHUB_OUTPUT
    - id: set-platform
      run: |
        if [ "${{ startsWith(github.event.ref, 'refs/tags/v') }}" == "true" ]; then
          echo "platform='linux/x86_64,linux/arm64'" >> $GITHUB_OUTPUT
        else
          echo "platform='linux/x86_64'" >> $GITHUB_OUTPUT
        fi

  build-toolkit:
    permissions:
      contents: read
    needs:
      - detect
    runs-on: ubuntu-latest
    env:
      PLATFORM: ${{ needs.detect.outputs.platform }}
    outputs:
      version: ${{ steps.version.outputs.version }}
    steps:
      - uses: actions/checkout@v4
        with:
          ref: "${{ github.event.pull_request.head.sha }}"
      - run: |
          git fetch --prune --unshallow
      - name: Define version
        id: version
        uses: ./.github/actions/version
      - name: Check cache for Toolkit image
        id: cache-toolkit
        uses: actions/cache/restore@v4
        env:
          cache-name: toolkit-build-x86_64-${{ github.event_name }}
          lookup-only: true
        with:
          path: /tmp/toolkit.tar
          key: ${{ env.cache-name }}-${{ steps.version.outputs.version }}
      - if: ${{ steps.cache-toolkit.outputs.cache-hit != 'true' }} 
        name: Build toolkit
        env:
          VERSION: ${{ steps.version.outputs.version }} 
        run: |
          make build-save
          mv build/elemental-toolkit*.tar /tmp/toolkit.tar
      - if: ${{ steps.cache-toolkit.outputs.cache-hit != 'true' }}
        name: Save toolkit image in cache
        id: save-toolkit
        uses: actions/cache/save@v4
        env:
          cache-name: toolkit-build-x86_64-${{ github.event_name }}
        with:
          path: /tmp/toolkit.tar
          key: ${{ env.cache-name }}-${{ steps.version.outputs.version }}

  build-matrix:
    needs:
      - detect
      - build-toolkit
    strategy:
      matrix:
        flavor: ${{fromJson(needs.detect.outputs.flavor)}}
      fail-fast: false
    uses: ./.github/workflows/build_and_test_x86.yaml
    with:
      flavor: ${{ matrix.flavor }}
      version: ${{ needs.build-toolkit.outputs.version }}
