name: Build and Upload Artifact
run-name: ${{ gitea.actor }} is running ${{ gitea.workflow }} on ${{ gitea.repository }}!

on: [push, pull_request]

jobs:
  build and upload-artifact:
    runs-on: ubuntu-latest
    steps:
      - name: Check out repository code
        uses: actions/checkout@v4.2.2
        with:
          submodules: true

      - name: Get latest CMake and Ninja
        uses: lukka/get-cmake@latest

      - name: Install Arm GNU Toolchain (arm-none-eabi-gcc)
        uses: carlosperate/arm-none-eabi-gcc-action@v1.10.0        

      - name: Create env
        run: |
          echo "REPO_NAME=$(echo $GITHUB_REPOSITORY | cut -d'/' -f2)" >> $GITHUB_ENV

      - name: Build
        run: |
          mkdir ./build
          cd ./build
          cmake -DCMAKE_BUILD_TYPE=Release ..
          make

      - name: Find autogen_version.c
        run: |
          AUTOGEN_VERSION_PATH=$(find . -name autogen_version.c)
          if [ -z "$AUTOGEN_VERSION_PATH" ]; then
            echo "Error: autogen_version.c not found"
            exit 1
          fi
          echo "AUTOGEN_VERSION_PATH=$AUTOGEN_VERSION_PATH" >> $GITHUB_ENV

      - name: Extract version
        run: |
          echo "VERSION=$(grep -oP 'g_version\s*=\s*"\K[^"]+' ${{ env.AUTOGEN_VERSION_PATH }})" >> $GITHUB_ENV
          echo ${{ env.VERSION }}

      - name: Upload Artifact
        if: github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/')
        uses: actions/upload-artifact@v3
        with:
          name: ${{ env.REPO_NAME }}-${{ env.VERSION }}
          path: |
            ./build/*.bin
            ./build/*.hex
            ./build/*.elf
