name: Source Code - Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: read

jobs:
  goreleaser:
    runs-on: ubuntu-latest
    permissions:
      contents: write # Grant write permissions to repository contents
      issues: write # Grant write permissions to PR milestones
    steps:
      - name: Checkout Repo
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          fetch-depth: 0

        # Extract title from latest version title in CHANGELOG.md
      - name: Prepare release title
        id: release-title
        run: |
          echo "title=$(grep -A 2 '<!-- next version -->' CHANGELOG.md | awk '/##/{print $2}')" >> $GITHUB_OUTPUT

      - name: Prepare release notes
        run: |
          touch release-notes.md
          echo "### Images and binaries here: https://github.com/open-telemetry/opentelemetry-collector-releases/releases/tag/${{ github.ref_name }}" >> release-notes.md
          echo "" >> release-notes.md
          echo "## End User Changelog" >> release-notes.md

          awk '/<!-- next version -->/,/<!-- previous-version -->/' CHANGELOG.md > tmp-chlog.md # select changelog of latest version only
          sed '1,3d' tmp-chlog.md >> release-notes.md # delete first 3 lines of file

          echo "" >> release-notes.md
          echo "## API Changelog" >> release-notes.md

          awk '/<!-- next version -->/,/<!-- previous-version -->/' CHANGELOG-API.md > tmp-chlog-api.md # select changelog of latest version only
          sed '1,3d' tmp-chlog-api.md >> release-notes.md # delete first 3 lines of file

      - name: Create Github Release
        run: |
          gh release create ${{ github.ref_name }} -t ${{ steps.release-title.outputs.title }} -F release-notes.md
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
        with:
          script: |
            const milestones = await github.rest.issues.listMilestones({
              owner: context.repo.owner,
              repo: context.repo.repo,
              state: "open"
            })
            for (const milestone of milestones.data) {
              if (milestone.title == "next release") {
                await github.rest.issues.updateMilestone({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  milestone_number: milestone.number,
                  title: "${{ github.ref_name }}"
                });
                await github.rest.issues.createMilestone({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  title: "next release"
                });
                return
              }
            }
