name: Release Readest

on:
  workflow_dispatch:
  release:
    types: [published]

jobs:
  get-release:
    permissions:
      contents: write
    runs-on: ubuntu-latest
    outputs:
      release_id: ${{ steps.get-release.outputs.release_id }}
      release_tag: ${{ steps.get-release.outputs.release_tag }}
      release_note: ${{ steps.get-release-notes.outputs.release_note }}
      release_version: ${{ steps.get-release-notes.outputs.release_version }}

    steps:
      - uses: actions/checkout@v4
      - name: setup node
        uses: actions/setup-node@v4
      - name: get version
        run: echo "PACKAGE_VERSION=$(node -p "require('./apps/readest-app/package.json').version")" >> $GITHUB_ENV
      - name: get release
        id: get-release
        uses: actions/github-script@v7
        with:
          script: |
            const { data } = await github.rest.repos.getLatestRelease({
              owner: context.repo.owner,
              repo: context.repo.repo,
            })
            core.setOutput('release_id', data.id);
            core.setOutput('release_tag', data.tag_name);
      - name: get release notes
        id: get-release-notes
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const version = require('./apps/readest-app/package.json').version;
            const releaseNotesFileContent = fs.readFileSync('./apps/readest-app/release-notes.json', 'utf8');
            const releaseNotes = JSON.parse(releaseNotesFileContent).releases[version] || {};
            const notes = releaseNotes.notes || [];
            const releaseNote = notes.map((note, index) => `${index + 1}. ${note}`).join(' ');
            console.log('Formatted release note:', releaseNote);
            core.setOutput('release_version', version);
            core.setOutput('release_note', releaseNote);

  build-tauri:
    needs: get-release
    permissions:
      contents: write
    strategy:
      fail-fast: false
      matrix:
        config:
          - os: ubuntu-22.04
            arch: x86_64
            rust_target: x86_64-unknown-linux-gnu
          - os: ubuntu-22.04-arm
            arch: aarch64
            rust_target: aarch64-unknown-linux-gnu
          - os: macos-latest
            arch: aarch64
            rust_target: x86_64-apple-darwin,aarch64-apple-darwin
            args: '--target universal-apple-darwin'
          - os: windows-latest
            arch: x86_64
            rust_target: x86_64-pc-windows-msvc
            args: '--target x86_64-pc-windows-msvc'
          - os: windows-latest
            arch: aarch64
            rust_target: aarch64-pc-windows-msvc
            args: '--target aarch64-pc-windows-msvc --bundles nsis'

    runs-on: ${{ matrix.config.os }}
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v4

      - name: initialize git submodules
        run: git submodule update --init --recursive

      - name: setup pnpm
        uses: pnpm/action-setup@v4
        with:
          version: 9.14.4

      - name: setup node
        uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: pnpm

      - name: install dependencies
        run: pnpm install

      - name: copy pdfjs-dist to public directory
        run: pnpm --filter @readest/readest-app setup-pdfjs

      - name: install Rust stable
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.config.rust_target }}

      - uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.config.os }}-cargo-${{ hashFiles('Cargo.lock') }}

      - name: create .env.local file for Next.js
        run: |
          echo "NEXT_PUBLIC_POSTHOG_KEY=${{ secrets.NEXT_PUBLIC_POSTHOG_KEY }}" >> .env.local
          echo "NEXT_PUBLIC_POSTHOG_HOST=${{ secrets.NEXT_PUBLIC_POSTHOG_HOST }}" >> .env.local
          echo "NEXT_PUBLIC_SUPABASE_URL=${{ secrets.NEXT_PUBLIC_SUPABASE_URL }}" >> .env.local
          echo "NEXT_PUBLIC_SUPABASE_ANON_KEY=${{ secrets.NEXT_PUBLIC_SUPABASE_ANON_KEY }}" >> .env.local
          echo "NEXT_PUBLIC_APP_PLATFORM=tauri" >> .env.local

      - name: copy .env.local to apps/readest-app
        run: cp .env.local apps/readest-app/.env.local

      - name: install dependencies (ubuntu only)
        if: contains(matrix.config.os, 'ubuntu')
        run: |
          sudo apt-get update
          sudo apt-get install -y pkg-config libfontconfig-dev libgtk-3-dev libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf xdg-utils

      - uses: tauri-apps/tauri-action@v0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
          TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
          APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
          APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
          APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
          APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
        with:
          projectPath: apps/readest-app
          releaseId: ${{ needs.get-release.outputs.release_id }}
          releaseBody: ${{ needs.get-release.outputs.release_note }}
          args: ${{ matrix.config.args || '' }}

      - name: upload portable binaries (Windows only)
        if: matrix.config.os == 'windows-latest'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        shell: bash
        run: |
          echo "Uploading Portable Binaries"
          arch=${{ matrix.config.arch }}
          version=${{ needs.get-release.outputs.release_version }}

          if [ "$arch" = "x86_64" ]; then
            bin_file="Readest_${version}_x64-portable.exe"
          elif [ "$arch" = "aarch64" ]; then
            bin_file="Readest_${version}_arm64-portable.exe"
          else
            echo "Unknown architecture: $arch"
            exit 1
          fi

          exe_file="target/${{ matrix.config.rust_target }}/release/readest.exe"
          # Browsers on Windows won't download zip files that contain exe files
          # so upload the exe files instead. This is totally stupid.
          # powershell.exe -Command "Compress-Archive -Path $exe_file -DestinationPath $bin_file -Force"
          cp $exe_file $bin_file

          echo "Uploading $bin_file to GitHub release"
          gh release upload ${{ needs.get-release.outputs.release_tag }} $bin_file --clobber

  update-release:
    permissions:
      contents: write
    runs-on: ubuntu-latest
    needs: [get-release, build-tauri]

    steps:
      - name: update release
        id: update-release
        uses: actions/github-script@v7
        env:
          release_id: ${{ needs.get-release.outputs.release_id }}
          release_tag: ${{ needs.get-release.outputs.release_tag }}
          release_note: ${{ needs.get-release.outputs.release_note }}
        with:
          script: |
            const { data } = await github.rest.repos.generateReleaseNotes({
              owner: context.repo.owner,
              repo: context.repo.repo,
              tag_name: process.env.release_tag,
            })
            const notes = process.env.release_note.split(/(?:\d\.\s)/).filter(Boolean);
            const formattedNotes = notes.map(note => `* ${note.trim()}`).join("\n");
            const body = `## Release Highlight\n${formattedNotes}\n\n${data.body}`;
            github.rest.repos.updateRelease({
              owner: context.repo.owner,
              repo: context.repo.repo,
              release_id: process.env.release_id,
              body: body,
              draft: false,
              prerelease: false
            })
