name: Publish (Beta)

permissions:
  contents: read

on:
  release:
    types: [published]

jobs:
  build:
    if: ${{ github.event.release.prerelease }}
    strategy:
      matrix:
        include:
          - configuration: Beta
            architecture: x64
          - configuration: Beta
            architecture: ARM64
      fail-fast: false

    uses: ./.github/workflows/reusable-build.yml
    with:
      configuration: ${{ matrix.configuration }}
      architecture: ${{ matrix.architecture }}
    secrets: inherit

  changelog:
    permissions:
      contents: write
    runs-on: ubuntu-latest
    continue-on-error: true
    if: ${{ github.event.release.prerelease }}
    steps:
      - name: Checkout all
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Install git-cliff
        uses: taiki-e/install-action@git-cliff

      - name: Generate changelog
        run: git-cliff --latest -o CHANGELOG.md

      - name: Add changelog to release
        uses: softprops/action-gh-release@v2.5.0
        with:
          tag_name: ${{ github.event.release.tag_name }}
          body_path: CHANGELOG.md
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  rename_and_release:
    permissions:
      contents: write
      actions: write
    needs: [build, changelog]
    runs-on: ubuntu-latest
    strategy:
      matrix:
        include:
          - configuration: Beta
            architecture: x64
          - configuration: Beta
            architecture: ARM64
    steps:
      - name: Download Build Artifact
        uses: actions/download-artifact@v4
        with:
          name: PCL2_CE_${{ matrix.configuration }}_${{ matrix.architecture }}
          path: ./artifact

      - name: Rename binaries
        run: |
          mv "./artifact/Plain Craft Launcher 2.exe" "PCL2_CE_${{ matrix.configuration }}_${{ matrix.architecture }}.exe"

      - name: Import GPG key
        uses: crazy-max/ghaction-import-gpg@v6
        with:
          gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }}
          passphrase: ${{ secrets.GPG_PASSPHRASE }}

      - name: Sign the binary
        run: |
          gpg --detach-sign --armor "PCL2_CE_${{ matrix.configuration }}_${{ matrix.architecture }}.exe"

      - name: Upload binary and signature to Release
        uses: softprops/action-gh-release@v2.2.2
        with:
          files: |
            PCL2_CE_${{ matrix.configuration }}_${{ matrix.architecture }}.exe
            PCL2_CE_${{ matrix.configuration }}_${{ matrix.architecture }}.exe.asc
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Trigger MirrorChyanUploading
        run: |
          gh workflow run --repo $GITHUB_REPOSITORY mirrorchyan_uploading.yml -f channel=beta -f arch=${{ matrix.architecture == 'x64' && 'x64' || 'arm64' }}
          gh workflow run --repo $GITHUB_REPOSITORY mirrorchyan_release_note.yml
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
