name: Build rpm package

on:
  workflow_dispatch:

env:
  FLUTTER_VERSION: "3.41.9"

jobs:
  build:
    runs-on: ubuntu-24.04
    outputs:
      version: ${{ steps.get_version.outputs.version }}

    steps:
      - uses: actions/checkout@v6

      - name: Get version from pubspec.yaml
        id: get_version
        run: |
          VERSION=$(sed -n 's/^version: \([0-9]*\.[0-9]*\.[0-9]*\).*/\1/p' app/pubspec.yaml)
          echo "version=$VERSION" >> $GITHUB_OUTPUT

  build_rpm:
    runs-on: ubuntu-latest
    container: fedora:38
    steps:
      - uses: actions/checkout@v6

      - name: Install dependencies
        run: sudo dnf install -y clang cmake gtk3-devel ninja-build libappindicator-gtk3-devel jq findutils which git patchelf rpm-build

      - uses: subosito/flutter-action@v2
        with:
          flutter-version: ${{ env.FLUTTER_VERSION }}
          channel: "stable"

      - name: Configure safe directory for Git
        run: git config --global --add safe.directory "/opt/hostedtoolcache/flutter/stable-${{ env.FLUTTER_VERSION }}-x64"

#      - name: Configure safe directory for Git (pub-cache)
#        run: git config --global --add safe.directory "/opt/hostedtoolcache/flutter/stable-${{ env.FLUTTER_VERSION }}-x64/.pub-cache"

      - name: Get flutter path
        run: which flutter

      - name: Get dart path
        run: which dart

      - name: Enable dart_distributor
        run: PUB_CACHE=/opt/hostedtoolcache/flutter/stable-${{ env.FLUTTER_VERSION }}-x64/.pub-cache dart pub global activate flutter_distributor

      - name: Debugging PATH and flutter_distributor
        run: |
          echo "PATH: $PATH"
          command -v flutter_distributor || echo "flutter_distributor not found"

      - name: Build rpm package
        working-directory: app
        run: FLUTTER_ROOT=/opt/hostedtoolcache/flutter/stable-${{ env.FLUTTER_VERSION }}-x64 flutter_distributor package --platform linux --targets rpm

      - name: Find rpm file
        id: find_rpm
        run: |
          VERSION=${{ needs.build.outputs.version }}
          RPM_PATH=$(find app/dist -name "localsend_app-$VERSION*-linux.rpm")
          echo "rpm_path=$RPM_PATH" >> $GITHUB_OUTPUT

      - name: Check if rpm file exists
        id: check_file
        run: |
          if [[ ! -f "${{ steps.find_rpm.outputs.rpm_path }}" ]]; then
            echo "File not found: ${{ steps.find_rpm.outputs.rpm_path }}"
            exit 1
          fi

      - name: Upload rpm file
        uses: actions/upload-artifact@v6
        with:
          name: rpm-result
          path: ${{ steps.find_rpm.outputs.rpm_path }}
