#
# Copyright (C) 2022-2024 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0

name: release

on:
  workflow_dispatch:
    inputs:
      version:
        description: 'Version to release'
        required: true
      branch:
        description: 'Branch to use for the release'
        required: true
        default: main
env:
  GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
  DEBUG: electron-builder

jobs:

  tag:
    name: Tagging
    runs-on: ubuntu-24.04
    outputs:
      githubTag: ${{ steps.TAG_UTIL.outputs.githubTag}}
      desktopVersion: ${{ steps.TAG_UTIL.outputs.desktopVersion}}
      releaseId: ${{ steps.create_release.outputs.id}}

    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.inputs.branch }}
      - name: Generate tag utilities
        id: TAG_UTIL
        run: |
            TAG_PATTERN=${{ github.event.inputs.version }}
            echo "githubTag=v$TAG_PATTERN" >> ${GITHUB_OUTPUT}
            echo "desktopVersion=$TAG_PATTERN" >> ${GITHUB_OUTPUT}

      - name: tag
        run: |
          git config --local user.name ${{ github.actor }}

          # Add the new version in package.json file
          sed -i  "s#version\":\ \"\(.*\)\",#version\":\ \"${{ steps.TAG_UTIL.outputs.desktopVersion }}\",#g" package.json
          find extensions/* -maxdepth 5 -name "package.json" | xargs -I {} sed -i "s#version\":\ \"\(.*\)\",#version\":\ \"${{ steps.TAG_UTIL.outputs.desktopVersion }}\",#g" {}
          git add package.json extensions/*/package.json extensions/*/packages/extension/package.json

          # Update the issue template with the new version and move old version below
          nextVersionLineNumber=$(grep -n "next (development version)" .github/ISSUE_TEMPLATE/bug_report.yml | cut -d ":" -f 1 | head -n 1)
          currentVersionItem=$(sed "$(expr ${nextVersionLineNumber} - 1)q;d" .github/ISSUE_TEMPLATE/bug_report.yml)
          newVersionItem=$(echo "$currentVersionItem" | sed -r -e "s|\".*\"|\"${{ steps.TAG_UTIL.outputs.desktopVersion }}\"|")
          # delete the lines before the next version line
          sed -i "$(expr ${nextVersionLineNumber} - 1)d" .github/ISSUE_TEMPLATE/bug_report.yml
          # insert the version being tagged
          sed -i "$(expr ${nextVersionLineNumber} - 1)i\\${newVersionItem}" .github/ISSUE_TEMPLATE/bug_report.yml
          sed -i "$(expr ${nextVersionLineNumber} + 1)i\\${currentVersionItem}" .github/ISSUE_TEMPLATE/bug_report.yml
          # add the changes
          git add .github/ISSUE_TEMPLATE/bug_report.yml

          # Add the new version in the appdata.xml file
          xmlReleasesLineNumber=$(grep -n "<releases>" .flatpak-appdata.xml | cut -d ":" -f 1 | head -n 1)
          newFlatpakReleaseItem="    <release version=\"${{ steps.TAG_UTIL.outputs.desktopVersion }}\" date=\"$(date +%Y-%m-%d)\"/>"
          sed -i "$(expr ${xmlReleasesLineNumber} + 1)i\\${newFlatpakReleaseItem}" .flatpak-appdata.xml
          git add .flatpak-appdata.xml

          # commit the changes
          git commit -m "chore: 🥁 tagging ${{ steps.TAG_UTIL.outputs.githubTag }} 🥳"
          echo "Tagging with ${{ steps.TAG_UTIL.outputs.githubTag }}"
          git tag ${{ steps.TAG_UTIL.outputs.githubTag }}
          git push origin ${{ steps.TAG_UTIL.outputs.githubTag }}
      - name: Create Release
        id: create_release
        uses: ncipollo/release-action@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag: ${{ steps.TAG_UTIL.outputs.githubTag }}
          name: ${{ steps.TAG_UTIL.outputs.githubTag }}
          draft: true
          prerelease: true
      - name: Create the PR to bump the version in the main branch (only if we're tagging from main branch)
        if: ${{ github.event.inputs.branch == 'main' }}
        run: |
          git config --local user.name ${{ github.actor }}
          git config --local user.email "fbenoit@redhat.com"
          CURRENT_VERSION=$(echo "${{ steps.TAG_UTIL.outputs.desktopVersion }}")
          tmp=${CURRENT_VERSION%.*}
          minor=${tmp#*.}
          bumpedVersion=${CURRENT_VERSION%%.*}.$((minor + 1)).0
          bumpedBranchName="bump-to-${bumpedVersion}"
          git checkout -b "${bumpedBranchName}"
          sed -i  "s#version\":\ \"\(.*\)\",#version\":\ \"${bumpedVersion}-next\",#g" package.json
          find extensions/* -maxdepth 5 -name "package.json" | xargs -I {} sed -i "s#version\":\ \"\(.*\)\",#version\":\ \"${bumpedVersion}-next\",#g" {}
          git add package.json extensions/*/package.json extensions/*/packages/extension/package.json
          git commit -s --amend -m "chore: bump version to ${bumpedVersion}"
          git push origin "${bumpedBranchName}"
          echo -e "📢 Bump version to ${bumpedVersion}\n\n${{ steps.TAG_UTIL.outputs.desktopVersion }} has been released.\n\n Time to switch to the new ${bumpedVersion} version 🥳" > /tmp/pr-title
          pullRequestUrl=$(gh pr create --title "chore: 📢 Bump version to ${bumpedVersion}" --body-file /tmp/pr-title --head "${bumpedBranchName}" --base "main")
          echo "📢 Pull request created: ${pullRequestUrl}"
          echo "➡️ Flag the PR as being ready for review"
          gh pr ready "${pullRequestUrl}"
          echo "🔅 Mark the PR as being ok to be merged automatically"
          gh pr merge "${pullRequestUrl}" --auto --rebase
        env:
          GITHUB_TOKEN: ${{ secrets.PODMAN_DESKTOP_BOT_TOKEN }}

  build:
    name: Build / ${{ matrix.os }} ${{ matrix.airgap == 'true' && '(Air Gap)' || ''  }}
    needs: tag
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        include:
          - os: "windows-2022"
          - os: "windows-2022"
            airgap: "true"
          - os: "macos-14"
          - os: "macos-14"
            airgap: "true"
          - os: "ubuntu-24.04"
    timeout-minutes: 60
    env:
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ needs.tag.outputs.githubTag}}

      - uses: pnpm/action-setup@v4
        name: Install pnpm
        with:
          run_install: false

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - uses: actions/setup-python@v5
        with:
          python-version: "3.x"

      - name: setup telemetry key for production
        run: |
          sed -i -r -e "s/SEGMENT_KEY = '.*'/SEGMENT_KEY = '${{ secrets.SEGMENT_WRITE_KEY }}'/" packages/main/src/plugin/telemetry/telemetry.ts

      - name: Execute pnpm
        run: pnpm install

      - name: Install flatpak on Linux
        if: ${{ matrix.os=='ubuntu-24.04' }}
        run: |
          sudo apt-get update
          sudo apt-get install flatpak -y
          sudo apt-get install flatpak-builder -y
          sudo apt-get install elfutils -y
          flatpak remote-add --if-not-exists flathub --user https://flathub.org/repo/flathub.flatpakrepo
          flatpak install flathub --no-static-deltas --user -y org.freedesktop.Platform//23.08 org.freedesktop.Sdk//23.08
      - name: Set macOS environment variables
        if: startsWith(matrix.os, 'macos')
        run: |
          echo "CSC_LINK=${{secrets.CSC_LINK}}" >> $GITHUB_ENV
          echo "CSC_KEY_PASSWORD=${{secrets.CSC_KEY_PASSWORD}}" >> $GITHUB_ENV
          echo "APPLE_ID=${{secrets.APPLE_ID}}" >> $GITHUB_ENV
          echo "APPLE_APP_SPECIFIC_PASSWORD=${{secrets.APPLE_APP_SPECIFIC_PASSWORD}}" >> $GITHUB_ENV
          echo "APPLE_TEAM_ID=${{secrets.APPLE_TEAM_ID}}" >> $GITHUB_ENV

      - name: Install Azure SignTool on Windows
        if: startsWith(matrix.os, 'windows')
        run: |
          dotnet tool install --global AzureSignTool --version 3.0.0
          echo "AZURE_KEY_VAULT_CERTIFICATE=${{secrets.AZURE_KEY_VAULT_CERTIFICATE}}" | Out-File -FilePath $env:GITHUB_ENV -Append
          echo "AZURE_KEY_VAULT_CLIENT_ID=${{secrets.AZURE_KEY_VAULT_CLIENT_ID}}" | Out-File -FilePath $env:GITHUB_ENV -Append
          echo "AZURE_KEY_VAULT_SECRET=${{secrets.AZURE_KEY_VAULT_SECRET}}" | Out-File -FilePath $env:GITHUB_ENV -Append
          echo "AZURE_KEY_VAULT_TENANT_ID=${{secrets.AZURE_KEY_VAULT_TENANT_ID}}" | Out-File -FilePath $env:GITHUB_ENV -Append
          echo "AZURE_KEY_VAULT_URL=${{secrets.AZURE_KEY_VAULT_URL}}" | Out-File -FilePath $env:GITHUB_ENV -Append

      - name: Run Build
        timeout-minutes: 40
        env:
          AIRGAP_DOWNLOAD: ${{ matrix.airgap == 'true' && '1' || ''  }}
        run: pnpm compile:next

  release:
    needs: [tag, build]
    name: Release
    runs-on: ubuntu-24.04
    steps:
      - name: id
        run: echo the release id is ${{ needs.tag.outputs.releaseId}}

      - name: Publish release
        uses: StuYarrow/publish-release@v1.1.2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          id: ${{ needs.tag.outputs.releaseId}}

  publish:
    needs: [tag, release]
    name: Publish
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
        name: Install pnpm
        with:
          run_install: false

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - name: Execute pnpm
        run: pnpm install

      - name: Set-up npmjs auth token
        run: printf "//registry.npmjs.org/:_authToken=${{ secrets.NPM_AUTH_TOKEN }}\n" >> ~/.npmrc

      - name: Publish API to npmjs
        run: |
          echo "Using version ${{ needs.tag.outputs.desktopVersion }}"
          sed -i  "s#version\":\ \"\(.*\)\",#version\":\ \"${{ needs.tag.outputs.desktopVersion }}\",#g" packages/extension-api/package.json
          cd packages/extension-api && pnpm publish --tag latest --no-git-checks --access public

      - name: Publish Webview API to npmjs
        run: |
          echo "Using version ${{ needs.tag.outputs.desktopVersion }}"
          sed -i  "s#version\":\ \"\(.*\)\",#version\":\ \"${{ needs.tag.outputs.desktopVersion }}\",#g" packages/webview-api/package.json
          cd packages/webview-api && pnpm publish --tag latest --no-git-checks --access public

      - name: Publish ui/svelte to npmjs
        run: |
          echo "Using version ${{ needs.tag.outputs.desktopVersion }}"
          sed -i  "s#version\":\ \"\(.*\)\",#version\":\ \"${{ needs.tag.outputs.desktopVersion }}\",#g" packages/ui/package.json
          cd packages/ui && pnpm build && pnpm publish --tag latest --no-git-checks --access public

      - name: Publish tests-playwright to npmjs
        run: |
          echo "Using version ${{ needs.tag.outputs.desktopVersion }}"
          sed -i  "s#version\":\ \"\(.*\)\",#version\":\ \"${{ needs.tag.outputs.desktopVersion }}\",#g" tests/playwright/package.json
          cd tests/playwright && pnpm build && pnpm publish --tag latest --no-git-checks --access public

      - name: Publish Podman Extension API to npmjs
        run: |
          echo "Using version ${{ needs.tag.outputs.desktopVersion }}"
          sed -i  "s#version\":\ \"\(.*\)\",#version\":\ \"${{ needs.tag.outputs.desktopVersion }}\",#g" extensions/podman/packages/api/package.json
          cd extensions/podman/packages/api
          pnpm publish --tag latest --no-git-checks --access public

  # publish the pnpm store for flathub builds
  pnpm-store:
    needs: [tag, release]
    name: pnpm-store-${{ matrix.arch }}
    runs-on: ubuntu-24.04
    strategy:
      matrix:
        arch: [amd64, arm64]

    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ needs.tag.outputs.githubTag}}

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
      - name: create the pnpm store from the dependencies
        run: |
          podman run --platform linux/${{ matrix.arch }} -v $(pwd):/project --rm -it --entrypoint=sh node:20 -c "cd /project && corepack enable pnpm && COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm install --frozen-lockfile  --store-dir pnpm-store"
          # now the store is in the pnpm-store directory
          # create a tarball of the store
          echo "Creating the archive store-cache-pnpm-${{ matrix.arch }}.tgz"
          tar -czf store-cache-pnpm-${{ matrix.arch }}.tgz pnpm-store

      - name: Upload binaries to release
        uses: svenstaro/upload-release-action@v2
        with:
          repo_token: ${{ secrets.GITHUB_TOKEN }}
          file: store-cache-pnpm-${{ matrix.arch }}.tgz
          tag: ${{ needs.tag.outputs.githubTag }}
