name: ci
run-name: "ci: ${{ github.event.pull_request.title }}"

on:
  pull_request:
    paths:
      - projects/**/*
      - .github/workflows/ci.yml

concurrency:
  group: ci/${{ github.event.pull_request.head.ref }}
  cancel-in-progress: true

jobs:
  plan:
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.process-diff.outputs.matrix }}
    steps:
      - uses: pkgxdev/setup@v2
      - uses: actions/checkout@v4
      - uses: technote-space/get-diff-action@v6
        id: get-diff
        with:
          PATTERNS: projects/**/package.yml
      - name: process diff
        id: process-diff
        env:
          PKGX_PANTRY_PATH: ${{ github.workspace }}
        run: |
          if [ -n "${{ steps.get-diff.outputs.diff }}" ]; then
            for x in ${{ steps.get-diff.outputs.diff }}; do
              y=$(echo $x | sed 's#projects/\(.*\)/[^/]*#\1#')
              RESULT="$RESULT ${y//$'\n'/}"
            done
          else
            RESULT="zlib.net kernel.org/linux-headers"
          fi

          ./.github/scripts/get-ci-matrix.ts $RESULT

      - run: echo '${{ steps.process-diff.outputs.matrix }}' | jq

  build:
    needs: plan
    strategy:
      fail-fast: false
      matrix:
        include: ${{ fromJSON(needs.plan.outputs.matrix) }}
    runs-on: ${{ matrix.platform.os }}
    container: ${{ matrix.platform.container }}
    name: ${{ matrix.pkg }} ${{ matrix.platform.tinyname }}
    env:
      PKGX_PANTRY_PATH: ${{ github.workspace }}
    steps:
      - uses: actions/checkout@v4

      - uses: ./.github/actions/setup
        with:
          p12-file-base64: ${{ secrets.APPLE_CERTIFICATE_P12 }}
          p12-password: ${{ secrets.APPLE_CERTIFICATE_P12_PASSWORD }}
          APPLE_IDENTITY: ${{ secrets.APPLE_IDENTITY }}

      - uses: pkgxdev/setup@v2
        with:
          PKGX_DIR: /opt

      - uses: pkgxdev/brewkit/build@v1
        id: build
        with:
          pkg: ${{ matrix.pkg }}

      - uses: pkgxdev/brewkit/audit@v1
        with:
          pkg: ${{ steps.build.outputs.pkgspec }}

      # prevent tests passing because the build directory is still there
      # requires `sudo` because `go` makes unremovable files…
      - name: wipe builds directory
        run: |
          if command -v sudo >/dev/null; then
            SUDO=sudo
          fi
          $SUDO rm -rf builds

      - uses: pkgxdev/brewkit/test@v1
        with:
          pkg: ${{ steps.build.outputs.pkgspec }}
