name: CI Tutorials

on:
  push:
    branches: [ main, develop ]
    tags: [ '*' ]
  pull_request:

# env:
#   APPS_EXCLUDED: |
#     ScrollMenu

jobs:
  prepare:
    runs-on: ubuntu-latest
    outputs:
      cmake_apps: ${{ steps.generate.outputs.cmake_apps }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Generate cmake apps list
        id: generate
        run: |
          python .github/scripts/generate-tutorials-app-list.py > cmake_apps.json
          cmake_apps=$(jq -c '.cmake_apps' cmake_apps.json)
          echo "cmake_apps=$cmake_apps" >> $GITHUB_OUTPUT

  cmake-build:
    runs-on: ubuntu-latest
    container: xanderhendriks/stm32cubeide:16.0
    needs: prepare
    strategy:
      matrix:
        app: ${{ fromJson(needs.prepare.outputs.cmake_apps) }}
    steps:
      - name: Setup GIT
        run: apt update && apt install -y git python3-full python3-pip python-is-python3 cmake

      - name: Checkout
        uses: actions/checkout@v5
        with:
          fetch-depth: 0

      - name: Install scripts requirements
        run: python3 -m pip install --break-system-packages -r Utilities/Scripts/app_packer/requirements.txt

      - name: Build ${{ matrix.app }}
        run: |
          echo "Setup environment"
          . ./Utilities/Scripts/build-cube/find-cube.sh
          export UNA_SDK=$GITHUB_WORKSPACE
          CMAKE_PATH="Docs/Tutorials/${{ matrix.app }}"
          CMAKE_ROOT=$(find "$CMAKE_PATH" -type f -name "CMakeLists.txt" | head -1 | xargs dirname)
          if [ -z "$CMAKE_ROOT" ] || [ ! -d "$CMAKE_ROOT" ]; then
            echo "No CMakeLists.txt found under $CMAKE_PATH"
            exit 1
          fi
          cd "$CMAKE_ROOT"
          mkdir -p build
          cd build
          echo "Build"
          cmake ..
          make -j$(nproc)

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.app }}-output
          path: Docs/Tutorials/${{ matrix.app }}/Output/

  release:
    runs-on: ubuntu-latest
    needs: cmake-build
    if: startsWith(github.ref, 'refs/tags/')
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts

      - name: Create release archive
        run: |
          zip -r tutorials-release.zip artifacts/

      - name: Release
        uses: softprops/action-gh-release@v2
        with:
          files: tutorials-release.zip
          generate_release_notes: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}