name: Firmware Build

on:
  push:
    branches: [main]
    tags: ['v*']
  pull_request:
    branches: [main]

env:
  ARDUINO_CLI_VERSION: 1.4.1

jobs:
  package:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: '3.12'

      - name: Install Arduino CLI
        run: |
          mkdir -p "$RUNNER_TEMP/arduino-cli"
          curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh \
            | BINDIR="$RUNNER_TEMP/arduino-cli" sh -s "$ARDUINO_CLI_VERSION"
          echo "$RUNNER_TEMP/arduino-cli" >> "$GITHUB_PATH"

      - name: Install Python tools
        run: pip install platformio esptool

      - name: Prepare RNode Arduino dependencies
        run: make -C vendor/rnode_firmware prep-esp32

      - name: Build release package
        run: make package

      - name: Upload firmware artifacts
        uses: actions/upload-artifact@v7
        with:
          name: rsdeck-dist
          path: dist/*

  release:
    needs: package
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v6

      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: '3.12'

      - name: Install Arduino CLI
        run: |
          mkdir -p "$RUNNER_TEMP/arduino-cli"
          curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh \
            | BINDIR="$RUNNER_TEMP/arduino-cli" sh -s "$ARDUINO_CLI_VERSION"
          echo "$RUNNER_TEMP/arduino-cli" >> "$GITHUB_PATH"

      - name: Install Python tools
        run: pip install platformio esptool

      - name: Prepare RNode Arduino dependencies
        run: make -C vendor/rnode_firmware prep-esp32

      - name: Build release package
        run: make package

      - name: Create Release
        env:
          GH_TOKEN: ${{ github.token }}
          GITHUB_TOKEN: ${{ github.token }}
          GH_REPO: ${{ github.repository }}
        run: |
          release_args=(--generate-notes)
          if [[ "$GITHUB_REF_NAME" == *-* ]]; then
            release_args+=(--prerelease)
          fi

          artifacts=(
            dist/rsdeck-full.zip
            dist/rsdeck-standalone.zip
            dist/rsdeck-rnode.zip
            dist/rsdeck-standalone-m5launcher.bin
            dist/rsdeck-rnode-m5launcher.bin
          )

          if gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
            gh release upload "$GITHUB_REF_NAME" "${artifacts[@]}" --clobber --repo "$GITHUB_REPOSITORY"
          else
            gh release create "$GITHUB_REF_NAME" "${artifacts[@]}" "${release_args[@]}" --repo "$GITHUB_REPOSITORY"
          fi
