name: Electron Master

defaults:
  run:
    shell: bash

env:
  CI: true

on:
  push:
    tags:
      - v**

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: false

jobs:
  build:
    # this is so the assets can be added to the release
    permissions:
      contents: write
    strategy:
      matrix:
        os:
          - ubuntu-22.04
          - windows-latest
          - macos-latest
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
      - if: ${{ startsWith(matrix.os, 'windows') }}
        run: pip.exe install setuptools
      - if: ${{ ! startsWith(matrix.os, 'windows') }}
        run: |
          mkdir .venv
          python3 -m venv .venv
          source .venv/bin/activate
          python3 -m pip install setuptools
      - name: Process release version
        id: process_version
        run: |
          echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
      - if: ${{ startsWith(matrix.os, 'ubuntu') }}
        name: Setup Flatpak dependencies
        run: |
          sudo apt-get update
          sudo apt-get install flatpak -y
          sudo apt-get install flatpak-builder -y
          sudo flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
          sudo flatpak install org.freedesktop.Sdk//24.08 -y
          sudo flatpak install org.freedesktop.Platform//24.08 -y
          sudo flatpak install org.electronjs.Electron2.BaseApp//24.08 -y
          sudo flatpak install org.flatpak.Builder -y

          METAINFO_FILE="packages/desktop-electron/extra-resources/linux/com.actualbudget.actual.metainfo.xml"
          TODAY=$(date +%Y-%m-%d)
          VERSION=${{ steps.process_version.outputs.version }}
          sed -i "s/%RELEASE_VERSION%/$VERSION/g; s/%RELEASE_DATE%/$TODAY/g" "$METAINFO_FILE"
          flatpak run --command=flatpak-builder-lint org.flatpak.Builder appstream "$METAINFO_FILE"
      - name: Set up environment
        uses: ./.github/actions/setup
      - name: Build Electron for Mac
        if: ${{ startsWith(matrix.os, 'macos') }}
        run: ./bin/package-electron
        env:
          CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
          CSC_LINK: ${{ secrets.CSC_LINK }}
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
          APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
      - name: Build Electron
        if: ${{ ! startsWith(matrix.os, 'macos') }}
        run: ./bin/package-electron
      - name: Upload Build
        uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
        with:
          name: actual-electron-${{ matrix.os }}
          path: |
            packages/desktop-electron/dist/*.dmg
            packages/desktop-electron/dist/*.exe
            !packages/desktop-electron/dist/Actual-windows.exe
            packages/desktop-electron/dist/*.AppImage
            packages/desktop-electron/dist/*.flatpak
      - name: Upload Windows Store Build
        if: ${{ startsWith(matrix.os, 'windows') }}
        uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
        with:
          name: actual-electron-${{ matrix.os }}-appx
          path: |
            packages/desktop-electron/dist/*.appx
      - name: Add to new release
        uses: softprops/action-gh-release@5be0e66d93ac7ed76da52eca8bb058f665c3a5fe # v2.4.2
        with:
          draft: true
          body: |
            :link: [View release notes](https://actualbudget.org/blog/release-${{ steps.process_version.outputs.version }})

            ## Desktop releases
            Please note: Microsoft store updates can sometimes lag behind the main release by a couple of days while they verify the new version.

            <p>
              <a href="https://apps.microsoft.com/detail/9p2hmlhsdbrm?cid=Github+Releases&mode=direct"><img src="https://get.microsoft.com/images/en-us%20dark.svg" width="200" /></a>
              <img src="data:image/gif;base64,R0lGODlhAQABAAAAACw=" width="12" height="1" alt="" />
              <a href="https://flathub.org/apps/com.actualbudget.actual"><img width="165" style="margin-left:12px;" alt="Get it on Flathub" src="https://flathub.org/api/badge?locale=en" /></a>
            </p>
          files: |
            packages/desktop-electron/dist/*.dmg
            packages/desktop-electron/dist/*.exe
            !packages/desktop-electron/dist/Actual-windows.exe
            packages/desktop-electron/dist/*.AppImage
            packages/desktop-electron/dist/*.flatpak

    outputs:
      version: ${{ steps.process_version.outputs.version }}

  publish-microsoft-store:
    needs: build
    runs-on: windows-latest
    if: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') }}
    steps:
      - name: Install StoreBroker
        shell: powershell
        run: |
          Install-Module -Name StoreBroker -AcceptLicense -Force -Scope CurrentUser -Verbose

      - name: Download Microsoft Store artifacts
        uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
        with:
          name: actual-electron-windows-latest-appx

      - name: Submit to Microsoft Store
        shell: powershell
        run: |
          # Disable telemetry
          $global:SBDisableTelemetry = $true

          # Authenticate against the store
          $pass = ConvertTo-SecureString -String '${{ secrets.MICROSOFT_STORE_CLIENT_SECRET }}' -AsPlainText -Force
          $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ${{ secrets.MICROSOFT_STORE_CLIENT_ID }},$pass
          Set-StoreBrokerAuthentication -TenantId '${{ secrets.MICROSOFT_STORE_TENANT_ID }}' -Credential $cred

          # Zip and create metadata files
          $artifacts = Get-ChildItem -Path . -Filter *.appx | Select-Object -ExpandProperty FullName
          New-StoreBrokerConfigFile -Path "$PWD/config.json" -AppId ${{ secrets.MICROSOFT_STORE_PRODUCT_ID }}
          New-SubmissionPackage -ConfigPath "$PWD/config.json" -DisableAutoPackageNameFormatting -AppxPath $artifacts -OutPath "$PWD" -OutName submission

          # Submit the app
          # See https://github.com/microsoft/StoreBroker/blob/master/Documentation/USAGE.md#the-easy-way
          Update-ApplicationSubmission `
            -AppId ${{ secrets.MICROSOFT_STORE_PRODUCT_ID }} `
            -SubmissionDataPath "submission.json" `
            -PackagePath "submission.zip" `
            -ReplacePackages `
            -NoStatus `
            -AutoCommit `
            -Force

  publish-flathub:
    needs: build
    runs-on: ubuntu-22.04
    if: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') }}
    steps:
      - name: Download Linux artifacts
        uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
        with:
          name: actual-electron-ubuntu-22.04

      - name: Calculate AppImage SHA256
        id: appimage_sha256
        run: |
          APPIMAGE_X64_SHA256=$(sha256sum Actual-linux-x86_64.AppImage | awk '{ print $1 }')
          APPIMAGE_ARM64_SHA256=$(sha256sum Actual-linux-arm64.AppImage | awk '{ print $1 }')
          echo "APPIMAGE_X64_SHA256=$APPIMAGE_X64_SHA256" >> "$GITHUB_ENV"
          echo "APPIMAGE_ARM64_SHA256=$APPIMAGE_ARM64_SHA256" >> "$GITHUB_ENV"

      - name: Checkout Flathub repo
        uses: actions/checkout@v6
        with:
          repository: flathub/com.actualbudget.actual
          token: ${{ secrets.FLATHUB_GITHUB_TOKEN }}

      - name: Update manifest with new SHA256
        run: |
          # Replace x86_64 entry
          sed -i "/x86_64.AppImage/{n;s|sha256:.*|sha256: ${{ env.APPIMAGE_X64_SHA256 }}|}" com.actualbudget.actual.yml
          sed -i "/x86_64.AppImage/s|url:.*|url: https://github.com/actualbudget/actual/releases/download/v${{ needs.build.outputs.version }}/Actual-linux-x86_64.AppImage|" com.actualbudget.actual.yml

          # Replace arm64 entry
          sed -i "/arm64.AppImage/{n;s|sha256:.*|sha256: ${{ env.APPIMAGE_ARM64_SHA256 }}|}" com.actualbudget.actual.yml
          sed -i "/arm64.AppImage/s|url:.*|url: https://github.com/actualbudget/actual/releases/download/v${{ needs.build.outputs.version }}/Actual-linux-arm64.AppImage|" com.actualbudget.actual.yml

          cat com.actualbudget.actual.yml

      - name: Create PR in Flathub repo
        uses: peter-evans/create-pull-request@v7
        with:
          token: ${{ secrets.FLATHUB_GITHUB_TOKEN }}
          commit-message: 'Update Actual flatpak to version ${{ needs.build.outputs.version }}'
          branch: 'release/${{ needs.build.outputs.version }}'
          draft: true
          title: 'Update Actual flatpak to version ${{ needs.build.outputs.version }}'
          body: |
            This PR updates the Actual desktop flatpak to version ${{ needs.build.outputs.version }}.

            :link: [View release notes](https://actualbudget.org/blog/release-${{ needs.build.outputs.version }})
          reviewers: 'jfdoming,MatissJanis,youngcw' # The core team that have accepted the collaborator access to the Flathub repo
