name: Build Flatpak

on:
  workflow_dispatch:
    inputs:
      version:
        description: "Version to build (e.g. 0.9.0)"
        required: true

permissions:
  contents: write

jobs:
  flatpak:
    name: Build Flatpak bundle
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Free up disk space
        run: |
          sudo rm -rf /usr/local/lib/android /opt/ghc /usr/share/dotnet /opt/hostedtoolcache/CodeQL
          sudo docker image prune -af || true

      - uses: pnpm/action-setup@v4
        with: { version: 10 }
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: pnpm

      - name: Build frontend and pack tarball
        run: |
          pnpm install --frozen-lockfile
          pnpm build:static
          tar -czf packaging/frontend-dist.tar.gz -C dist .

      - name: Compute frontend-dist sha256
        run: |
          SHA=$(sha256sum packaging/frontend-dist.tar.gz | awk '{print $1}')
          echo "FRONTEND_SHA=$SHA" >> $GITHUB_ENV
          echo "frontend-dist.tar.gz sha256: $SHA"

      - name: Patch frontend-dist sha256 in flatpak manifest
        run: |
          python3 -c "
          import re, pathlib, os
          p = pathlib.Path('io.github.moku_project.Moku.yml')
          content = p.read_text()
          # Replace the sha256 line that follows the frontend-dist.tar.gz source entry
          content = re.sub(
              r'(path: packaging/frontend-dist\.tar\.gz\n\s+sha256: )[0-9a-f]{64}',
              r'\g<1>' + os.environ['FRONTEND_SHA'],
              content
          )
          p.write_text(content)
          "

      - name: Install flatpak tooling
        run: |
          sudo apt-get update
          sudo apt-get install -y flatpak flatpak-builder
          flatpak --user remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo

      - name: Cache flatpak runtimes/SDKs
        uses: actions/cache@v4
        with:
          path: ~/.local/share/flatpak
          key: flatpak-runtimes-gnome48-rust-stable

      - name: Install runtime and SDK
        run: |
          flatpak --user install -y --noninteractive flathub \
            org.gnome.Platform//48 \
            org.gnome.Sdk//48

      - name: Build flatpak
        run: |
          rm -rf build-dir repo
          flatpak-builder \
            --user \
            --install-deps-from=flathub \
            --repo=repo \
            --force-clean \
            build-dir \
            io.github.moku_project.Moku.yml

      - name: Bundle flatpak
        run: |
          flatpak build-bundle \
            --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo \
            repo \
            moku.flatpak \
            io.github.moku_project.Moku

      - name: Upload Flatpak artifact to release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          # Poll for up to 10 minutes — the release is created by the Windows workflow
          # which may still be building when the flatpak bundle finishes.
          for i in $(seq 1 40); do
            RELEASE_ID=$(curl -s -H "Authorization: Bearer $GITHUB_TOKEN" \
              "https://api.github.com/repos/moku-project/Moku/releases" \
              | jq -r '.[] | select(.tag_name == "v${{ github.event.inputs.version }}") | .id' | head -1)
            [ -n "$RELEASE_ID" ] && break
            echo "Waiting for release... attempt $i/40"; sleep 15
          done
          [ -z "$RELEASE_ID" ] && { echo "ERROR: release not found after polling"; exit 1; }

          curl -s -X POST \
            -H "Authorization: Bearer $GITHUB_TOKEN" \
            -H "Content-Type: application/octet-stream" \
            --data-binary @"moku.flatpak" \
            "https://uploads.github.com/repos/moku-project/Moku/releases/$RELEASE_ID/assets?name=moku.flatpak"
