name: Build

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]

jobs:
  Gen_Matrix:
    outputs:
      matrix: ${{ steps.files.outputs.matrix }}
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Generate Matrix of all examples
      id: files
      run: |
        JSONI=$(find . -name platformio.ini -type f | sed 's,/platformio.ini$,,' | xargs -n 1 -I {} echo -e '"{}",')

        # Remove last "," and add closing brackets
        if [[ $JSONI == *, ]]; then
        JSONI="${JSONI%?}"
        fi
        JSONI=${JSONI//$'\n'}
        echo $JSONI
        # Set output
        echo "::set-output name=matrix::[${JSONI}]"
  Build_Example:
    needs: Gen_Matrix
    runs-on: ubuntu-latest
    strategy:
      matrix:
        project: ${{fromJson(needs.Gen_Matrix.outputs.matrix)}}

    steps:
    - uses: actions/checkout@v2
    - name: Cache pip
      uses: actions/cache@v2
      with:
        path: ~/.cache/pip
        key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
        restore-keys: |
          ${{ runner.os }}-pip-
    - name: Cache PlatformIO
      uses: actions/cache@v2
      with:
        path: ~/.platformio
        key: ${{ runner.os }}-${{ hashFiles('**/platformio.ini') }}
    - name: Cache PlatformIO build
      uses: actions/cache@v2
      with:
        path: .pio
        key: pio-${{ runner.os }}-${{ matrix.project }}
        restore-keys: |
          pio-${{ runner.os }}-
          pio-
    - name: Set up Python
      uses: actions/setup-python@v2
    - name: Install PlatformIO
      run: |
        python -m pip install --upgrade pip
        pip install --upgrade platformio
    - name: Build example
      env:
        PLATFORMIO_BUILD_CACHE_DIR: "../../.pio/buildcache"
      run: pio run --jobs 2 --project-dir ${{ matrix.project }}

  Build_Examples:
    needs: Build_Example
    runs-on: ubuntu-latest
    steps:
    - name: done
      run: echo ok
