name: Build arm64 deb

on:
  workflow_dispatch:

env:
  FLUTTER_VERSION: "3.13.9"

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

    steps:
      - uses: actions/checkout@v4

      - 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

  # Manage the Flutter version on the self-hosted runner manually!
  # Flutter currently doesn't provide Linux ARM64 binaries.
  build_deb_arm_64:
    needs: build
    runs-on: [self-hosted, linux, arm64]

    steps:
      - uses: actions/checkout@v4

      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y clang cmake libgtk-3-dev ninja-build libayatana-appindicator3-dev

      - name: Enable dart_distributor
        run: dart pub global activate flutter_distributor

      - name: Build deb package
        working-directory: app
        run: PATH="$PATH:$HOME/.pub-cache/bin" flutter_distributor package --platform linux --targets deb

      - name: Find deb file
        id: find_deb
        run: |
          VERSION=${{ needs.build.outputs.version }}
          DEB_PATH=$(find app/dist -name "localsend_app-$VERSION*-linux.deb")
          echo "deb_path=$DEB_PATH" >> $GITHUB_OUTPUT

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

      # Remove this when: https://github.com/leanflutter/flutter_distributor/pull/150 is merged
      - name: Update Architecture
        run: |
          mkdir temp
          cd temp
          ar x ../${{ steps.find_deb.outputs.deb_path }}
          tar xJf control.tar.xz --overwrite
          sed -i '/Architecture:/c\Architecture: arm64' ./control
          tar cJf control.tar.xz control postinst postrm
          ar rcs ../${{ steps.find_deb.outputs.deb_path }} debian-binary control.tar.xz data.tar.xz

      - name: Upload deb file
        uses: actions/upload-artifact@v3
        with:
          name: deb-arm-64-result
          path: ${{ steps.find_deb.outputs.deb_path }}
