name: Build All & Release
on:
  push:
    branches: [master, release/*, test/git-actions]
    tags:
      - v*

permissions:
  contents: write

jobs:
  create-release:
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v')
    steps:
      - name: Checkout
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
        with:
          fetch-depth: 0
      - name: Generate release body
        env:
          GH_REPOSITORY: ${{ github.repository }}
          GH_REF_NAME: ${{ github.ref_name }}
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          if echo "$GH_REF_NAME" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
            PREV_TAG=$(git tag --merged HEAD --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | grep -v "^${GH_REF_NAME}$" | sed -n '1p')
          else
            PREV_TAG=$(git tag --merged HEAD --sort=-v:refname | grep '^v' | grep -v "^${GH_REF_NAME}$" | sed -n '1p')
          fi

          # Contributor attribution was lost when curated notes replaced GitHub's
          # auto-generated ones; pull the generated notes only to extract it.
          GENERATED_NOTES=""
          if [ -n "$PREV_TAG" ]; then
            GENERATED_NOTES=$(gh api "repos/${GH_REPOSITORY}/releases/generate-notes" \
              -f tag_name="$GH_REF_NAME" -f previous_tag_name="$PREV_TAG" --jq .body) \
              || { GENERATED_NOTES=""; echo "Could not fetch generated notes for contributor extraction"; }
          fi
          CONTRIBUTORS=$(printf '%s\n' "$GENERATED_NOTES" \
            | grep -oE ' by @[[:alnum:]-]+(\[bot\])? in https://[^ ]+/pull/[0-9]+$' \
            | sed 's/^ by //;s/ in .*//' | grep -v '\[bot\]$' | sort -fu | paste -sd ' ' -) || true
          NEW_CONTRIBUTORS=$(printf '%s\n' "$GENERATED_NOTES" \
            | awk '/^## New Contributors$/{f=1} /^\*\*Full Changelog/{f=0} f' \
            | sed 's/^## /### /') || true

          {
            cat build/release-notes.md
            if [ -n "$CONTRIBUTORS" ]; then
              echo ""
              echo "### Contributors"
              echo ""
              echo "Thanks to everyone who contributed to this release: $CONTRIBUTORS"
            fi
            if [ -n "$NEW_CONTRIBUTORS" ]; then
              echo ""
              echo "$NEW_CONTRIBUTORS"
            fi
            echo ""
            if [ -n "$PREV_TAG" ]; then
              echo "**Full Changelog**: https://github.com/${GH_REPOSITORY}/compare/${PREV_TAG}...${GH_REF_NAME}"
            fi
          } > /tmp/release-body.md
      - name: Create Draft Release
        uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3.0.1
        with:
          tag_name: ${{ github.ref_name }}
          draft: true
          prerelease: ${{ contains(github.ref, 'RC') || contains(github.ref, 'beta') || contains(github.ref, 'alpha') }}
          body_path: /tmp/release-body.md

  linux-bin-and-snap-release:
    runs-on: ubuntu-latest
    env:
      SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}
      UNSPLASH_KEY: ${{ secrets.UNSPLASH_KEY }}
      UNSPLASH_CLIENT_ID: ${{ secrets.UNSPLASH_CLIENT_ID }}

    steps:
      - name: Check out Git repository
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
        with:
          persist-credentials: false

      - name: Setup Electron build environment
        uses: ./.github/actions/setup-electron-build

      - name: Install npm Packages
        uses: nick-fields/retry@ce71cc2ab81d554ebbe88c79ab5975992d79ba08 # v3
        with:
          timeout_minutes: 10
          max_attempts: 3
          retry_wait_seconds: 15
          shell: bash
          # Retry electron's flaky postinstall binary download. Drop
          # node_modules/electron between tries so npm re-runs the postinstall
          # (a plain re-`npm i` skips scripts for an already-present package).
          command: npm i || { rm -rf node_modules/electron; exit 1; }

      - name: Install Playwright Browsers
        run: |
          npx playwright install --with-deps chromium
          npx playwright install-deps chromium

      - run: npm run env # Generate env.generated.ts

      - name: Lint
        run: npm run lint

      - name: Test Unit
        run: npm run test

      - name: Build Frontend for E2E
        run: npm run buildFrontend:e2e

      - name: Verify Build Output
        run: |
          test -f .tmp/angular-dist/browser/index.html || (echo "Build output missing" && exit 1)
          test -f .tmp/angular-dist/browser/assets/bundled-plugins/api-test-plugin/manifest.json || (echo "Plugin assets missing from build" && exit 1)

      - name: Test E2E
        run: npm run e2e:ci

      - name: 'Upload E2E results on failure'
        if: ${{ failure() }}
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: e2eResults
          path: .tmp/e2e-test-results/**/*.*
          retention-days: 14

      - name: Build Frontend & Electron
        run: npm run build

      - name: Build/Release Electron app
        if: startsWith(github.ref, 'refs/tags/v')
        uses: johannesjo/action-electron-builder@9ea9e2d991c97668843d57337848e3e2b1ffab3d # v1
        with:
          build_script_name: empty
          github_token: ${{ secrets.github_token }}
          release: true

      - name: Build Electron app
        if: false == startsWith(github.ref, 'refs/tags/v')
        uses: johannesjo/action-electron-builder@9ea9e2d991c97668843d57337848e3e2b1ffab3d # v1
        with:
          build_script_name: empty
          github_token: ${{ secrets.github_token }}
          release: false
          args: '--publish never'

      - name: Normalize snap file name
        if: false == startsWith(github.ref, 'refs/tags/v')
        run: find ./.tmp/app-builds -type f -name '*.snap' -exec sh -c 'x="{}"; mv "$x" ".tmp/app-builds/sp.snap"' \;

      - name: Check for final release tag on this commit
        id: release-tag
        if: false == startsWith(github.ref, 'refs/tags/v')
        run: |
          git fetch --force --tags origin 'refs/tags/v*:refs/tags/v*'
          if git tag --points-at HEAD | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
            echo "has_final_release_tag=true" >> "$GITHUB_OUTPUT"
          else
            echo "has_final_release_tag=false" >> "$GITHUB_OUTPUT"
          fi
      # Upload branch builds to edge. Published releases upload the exact
      # GitHub release snap to edge/stable in build-publish-to-snap-on-release.yml.
      # Uses Canonical's official snapcraft container instead of `sudo snap
      # install snapcraft --classic` on the runner, which has been a recurring
      # source of "unable to contact snap store" failures.
      # The container runs snapcraft as a pebble service whose working-dir is
      # hard-coded to /project, so docker's -w flag is ignored — mount the
      # build dir at /project so `snapcraft upload sp.snap` resolves correctly.
      - name: Upload branch snap to edge
        if: false == startsWith(github.ref, 'refs/tags/v') && steps.release-tag.outputs.has_final_release_tag != 'true'
        uses: nick-fields/retry@ce71cc2ab81d554ebbe88c79ab5975992d79ba08 # v3
        with:
          max_attempts: 3
          timeout_minutes: 15
          retry_wait_seconds: 60
          # The snapcraft-rocks image's wrapper already runs `snapcraft "$@"`,
          # so the docker CMD must NOT include a leading `snapcraft` word —
          # that gets passed as the subcommand and snapcraft errors with
          # "no such command 'snapcraft'".
          command: |
            docker run --rm \
              -v "$PWD/.tmp/app-builds:/project" \
              -e SNAPCRAFT_STORE_CREDENTIALS \
              -e SNAPCRAFT_HAS_TTY=true \
              ghcr.io/canonical/snapcraft:8_core24 \
              upload sp.snap --release edge
        env:
          SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}
      #      - run: snapcraft push .tmp/app-builds/sp.snap --release candidate
      #        if: startsWith(github.ref, 'refs/tags/v')
  #      - run: snapcraft promote superproductivity --from-channel latest/edge --to-channel latest/candidate --yes
  #        if: startsWith(github.ref, 'refs/tags/v')

  mac-bin:
    needs: [create-release]
    runs-on: macos-15
    if: startsWith(github.ref, 'refs/tags/v')
    env:
      UNSPLASH_KEY: ${{ secrets.UNSPLASH_KEY }}
      UNSPLASH_CLIENT_ID: ${{ secrets.UNSPLASH_CLIENT_ID }}

    steps:
      - name: Check out Git repository
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
        with:
          persist-credentials: false

      - name: Echo is Release
        run: echo "IS_RELEASE $IS_RELEASE, ${{ startsWith(github.ref, 'refs/tags/v') }}"
        env:
          IS_RELEASE: ${{ startsWith(github.ref, 'refs/tags/v') }}

      - name: Setup Electron build environment
        uses: ./.github/actions/setup-electron-build

      # @nx/nx-darwin-arm64 + dmg-license aren't in package.json (npm's
      # optional-dep bug skips them), so install them explicitly. That install
      # and `npm i` both run electron's flaky postinstall binary download, so
      # retry the whole thing — dropping node_modules/electron between tries
      # forces the postinstall to re-run (npm skips it for a present package).
      - name: Install npm Packages
        uses: nick-fields/retry@ce71cc2ab81d554ebbe88c79ab5975992d79ba08 # v3
        with:
          timeout_minutes: 10
          max_attempts: 3
          retry_wait_seconds: 15
          shell: bash
          command: npm install @nx/nx-darwin-arm64 dmg-license && npm i || { rm -rf node_modules/electron; exit 1; }

      - run: 'echo "$PROVISION_PROFILE" | base64 --decode > embedded.provisionprofile'
        shell: bash
        env:
          PROVISION_PROFILE: ${{secrets.dl_provision_profile}}

      - name: Prepare for app notarization
        # Import Apple API key for app notarization on macOS
        run: |
          mkdir -p ~/private_keys/
          echo '${{ secrets.mac_api_key }}' > ~/private_keys/AuthKey_${{ secrets.mac_api_key_id }}.p8

      - run: npm run env # Generate env.generated.ts

      - name: Lint
        run: npm run lint

      - name: Test Unit
        run: npm run test
        env:
          NODE_OPTIONS: '--max-old-space-size=4096'

      #      - uses: browser-actions/setup-chrome@v2
      #        id: setup-chrome
      #      - run: |
      #          echo Installed chromium version: ${{ steps.setup-chrome.outputs.chrome-version }}
      #          ${{ steps.setup-chrome.outputs.chrome-path }} --version
      # Disabled because not working atm: https://github.com/super-productivity/super-productivity/actions/runs/5924016145/job/16060737982
      #      - name: Test E2E
      #        run: npm run e2e

      - name: Build Frontend & Electron
        run: npm run build

      - name: Build/Release Electron app
        uses: johannesjo/action-electron-builder@9ea9e2d991c97668843d57337848e3e2b1ffab3d # v1
        with:
          build_script_name: empty
          github_token: ${{ secrets.github_token }}
          mac_certs: ${{ secrets.mac_certs }}
          mac_certs_password: ${{ secrets.mac_certs_password }}
          release: ${{ startsWith(github.ref, 'refs/tags/v') }}
          # macOS notarization API key
        env:
          API_KEY_ID: ${{ secrets.mac_api_key_id }}
          API_KEY_ISSUER_ID: ${{ secrets.mac_api_key_issuer_id }}
          APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}

  windows-bin:
    needs: [create-release]
    runs-on: windows-latest
    if: startsWith(github.ref, 'refs/tags/v')
    permissions:
      contents: write
      actions: read # Required by SignPath action
      id-token: write # Required for SignPath origin verification
    env:
      UNSPLASH_KEY: ${{ secrets.UNSPLASH_KEY }}
      UNSPLASH_CLIENT_ID: ${{ secrets.UNSPLASH_CLIENT_ID }}

    steps:
      # required because setting via env.TZ does not work on windows
      - name: Set timezone to Europe Standard Time
        uses: szenius/set-timezone@1f9716b0f7120e344f0c62bb7b1ee98819aefd42 # v2.0
        with:
          timezoneWindows: 'W. Europe Standard Time'

      - name: Check out Git repository
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6
        with:
          persist-credentials: false

      - name: Setup Electron build environment
        uses: ./.github/actions/setup-electron-build

      # @nx/nx-win32-x64-msvc isn't in package.json (npm's optional-dep bug
      # skips it), so install it explicitly. That install and `npm i` both run
      # electron's flaky postinstall binary download, so retry the whole thing
      # — dropping node_modules/electron between tries forces the postinstall
      # to re-run (npm skips it for a present package).
      - name: Install npm Packages
        uses: nick-fields/retry@ce71cc2ab81d554ebbe88c79ab5975992d79ba08 # v3
        with:
          timeout_minutes: 10
          max_attempts: 3
          retry_wait_seconds: 15
          shell: bash
          command: npm install @nx/nx-win32-x64-msvc && npm i || { rm -rf node_modules/electron; exit 1; }

      - name: Setup Chrome
        id: setup-chrome
        uses: browser-actions/setup-chrome@2e1d749697dd1612b833dba4a722266286fbefcd # v2

      - name: Export Chrome path for Karma
        shell: pwsh
        run: echo "CHROME_BIN=${{ steps.setup-chrome.outputs.chrome-path }}" >> $env:GITHUB_ENV

      - run: npm run env # Generate env.generated.ts

      - name: Lint
        run: npm run lint

      - name: Test Unit
        run: npm run test

      - name: Build Frontend & Electron
        run: npm run build

      - name: Build/Release Electron app
        uses: johannesjo/action-electron-builder@9ea9e2d991c97668843d57337848e3e2b1ffab3d # v1
        with:
          build_script_name: empty
          github_token: ${{ secrets.github_token }}
          release: false
          args: '--publish never' # Explicit: don't auto-publish unsigned exe files

      # --- Code signing (must succeed — we never publish unsigned exe files) ---

      - name: Upload unsigned executables for SignPath
        id: upload-unsigned
        uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
        with:
          name: unsigned-windows-executables
          path: .tmp/app-builds/*.exe
          if-no-files-found: error
          retention-days: 1

      - name: Sign Windows executables with SignPath
        uses: signpath/github-action-submit-signing-request@b9d91eadd323de506c0c81cf0c7fe7438f3360fd # v2
        with:
          api-token: ${{ secrets.SIGNPATH_API_TOKEN }}
          organization-id: ${{ secrets.SIGNPATH_ORGANIZATION_ID }}
          project-slug: super-productivity
          signing-policy-slug: 'release-signing'
          artifact-configuration-slug: 'github-zip-pe'
          github-artifact-id: ${{ steps.upload-unsigned.outputs.artifact-id }}
          output-artifact-directory: '.tmp/app-builds-signed/'
          wait-for-completion: true
          wait-for-completion-timeout-in-seconds: 3600

      - name: Move signed executables back to build directory
        shell: pwsh
        run: |
          $signed = Get-ChildItem -Path .tmp/app-builds-signed -Filter *.exe -Recurse
          if ($signed.Count -eq 0) {
            Write-Error "No signed executables found in SignPath output directory"
            exit 1
          }
          # Build a map of original filenames for matching
          # SignPath may alter separators in filenames, so we normalize
          # dots, hyphens, and spaces to find the corresponding original file
          $originals = Get-ChildItem -Path .tmp/app-builds -Filter *.exe
          $signed | ForEach-Object {
            $signedName = $_.Name
            $normalizedSigned = $signedName -replace '[.\-\s]', ''
            $match = $originals | Where-Object { ($_.Name -replace '[.\-\s]', '') -eq $normalizedSigned }
            if ($match -is [array]) {
              Write-Error "Ambiguous match for $signedName — matched multiple originals: $($match.Name -join ', ')"
              exit 1
            }
            if ($match) {
              Write-Host "Replacing $($match.Name) with signed version (was: $signedName)"
              Move-Item -Force $_.FullName $match.FullName
            } else {
              Write-Error "No matching original found for signed file: $signedName"
              exit 1
            }
          }
          Write-Host "Final executables:"
          Get-ChildItem -Path .tmp/app-builds -Filter *.exe | Format-Table -AutoSize

      - name: Verify code signatures
        shell: pwsh
        run: |
          $exeFiles = Get-ChildItem -Path .tmp/app-builds -Filter *.exe
          foreach ($exe in $exeFiles) {
            $sig = Get-AuthenticodeSignature $exe.FullName
            Write-Host "$($exe.Name): $($sig.Status)"
            if ($sig.Status -ne 'Valid') {
              Write-Error "Signature verification failed for $($exe.Name): $($sig.Status)"
              exit 1
            }
          }

      - name: Regenerate blockmaps and generate latest.yml for signed executables
        shell: pwsh
        run: |
          $buildDir = ".tmp/app-builds"
          # Only regenerate blockmaps for NSIS setup files (portables don't use them)
          $setupExes = Get-ChildItem -Path $buildDir -Filter "Super-Productivity-Setup*.exe"

          # Resolve the platform-specific app-builder binary from the lockfile-pinned package
          $appBuilder = node -e "console.log(require('app-builder-bin').appBuilderPath)"

          foreach ($exe in $setupExes) {
            $blockmapPath = "$($exe.FullName).blockmap"
            Write-Host "Regenerating blockmap for $($exe.Name)..."
            $output = & $appBuilder blockmap --input="$($exe.FullName)" --output="$blockmapPath" --compression=gzip
            Write-Host "  blockmap output: $output"
          }

          # Update latest.yml with hashes from signed executables
          # (electron-builder generates it during build, but with hashes of unsigned files)
          node -e "
            const fs = require('fs');
            const path = require('path');
            const yaml = require('js-yaml');
            const crypto = require('crypto');

            const buildDir = '.tmp/app-builds';
            const ymlPath = path.join(buildDir, 'latest.yml');

            function getFileInfo(filePath) {
              const fileBuffer = fs.readFileSync(filePath);
              const info = {
                sha512: crypto.createHash('sha512').update(fileBuffer).digest('base64'),
                size: fileBuffer.length,
              };
              const blockmapPath = filePath + '.blockmap';
              if (fs.existsSync(blockmapPath)) {
                info.blockMapSize = fs.statSync(blockmapPath).size;
              }
              return info;
            }

            if (fs.existsSync(ymlPath)) {
              // Update existing latest.yml (preserves all electron-builder fields)
              const ymlData = yaml.load(fs.readFileSync(ymlPath, 'utf8'));
              if (!ymlData.files || ymlData.files.length === 0) {
                console.error('ERROR: latest.yml has no file entries');
                process.exit(1);
              }
              for (const fileEntry of ymlData.files) {
                const filePath = path.join(buildDir, fileEntry.url);
                if (!fs.existsSync(filePath)) {
                  console.error('ERROR: File referenced in latest.yml not found: ' + fileEntry.url);
                  process.exit(1);
                }
                const info = getFileInfo(filePath);
                Object.assign(fileEntry, info);
                console.log('  Updated ' + fileEntry.url + ': sha512=' + info.sha512.substring(0, 20) + '... size=' + info.size);
              }
              if (ymlData.path) {
                const primary = ymlData.files.find(f => f.url === ymlData.path);
                if (primary) { ymlData.sha512 = primary.sha512; }
              }
              fs.writeFileSync(ymlPath, yaml.dump(ymlData, { lineWidth: -1 }));
              console.log('latest.yml updated with signed file hashes');
            } else {
              // Fallback: generate from scratch if latest.yml was not created
              console.log('No existing latest.yml found, generating from scratch');
              const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
              const setupExes = fs.readdirSync(buildDir)
                .filter(f => f.startsWith('Super-Productivity-Setup') && f.endsWith('.exe'));
              if (setupExes.length === 0) {
                console.error('ERROR: No setup executables found in ' + buildDir);
                process.exit(1);
              }
              const files = setupExes.map(filename => {
                const filePath = path.join(buildDir, filename);
                const info = getFileInfo(filePath);
                console.log('  ' + filename + ': sha512=' + info.sha512.substring(0, 20) + '... size=' + info.size);
                return { url: filename, ...info };
              });
              const primary = files.find(f => f.url === 'Super-Productivity-Setup.exe')
                || files.find(f => f.url === 'Super-Productivity-Setup-x64.exe')
                || files[0];
              const latestYml = {
                version: pkg.version,
                files,
                path: primary.url,
                sha512: primary.sha512,
                releaseDate: new Date().toISOString(),
              };
              fs.writeFileSync(ymlPath, yaml.dump(latestYml, { lineWidth: -1 }));
              console.log('Generated latest.yml for ' + files.length + ' signed executables');
            }
          "

      - name: Publish signed Windows binaries to GitHub Release
        uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3.0.1
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          files: |
            .tmp/app-builds/*.exe
            .tmp/app-builds/Super-Productivity-Setup*.blockmap
            .tmp/app-builds/latest*.yml
          draft: true
          prerelease: ${{ contains(github.ref, 'RC') || contains(github.ref, 'beta') || contains(github.ref, 'alpha') }}
