name: Release
on:
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Set up JDK for running Gradle
        uses: actions/setup-java@v3
        with:
          distribution: temurin
          java-version: 17

      - uses: gradle/gradle-build-action@v2
        name: Build
        with:
          arguments: build

      - uses: actions/upload-artifact@v3
        name: Save unit test results
        if: always()
        with:
          name: test-results
          path: jmx-metrics/build/reports/tests/test

  integration-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Set up JDK for running Gradle
        uses: actions/setup-java@v3
        with:
          distribution: temurin
          java-version: 17

      - uses: gradle/gradle-build-action@v2
        name: Integration test
        with:
          arguments: integrationTest

      - uses: actions/upload-artifact@v3
        name: Save integration test results
        if: always()
        with:
          name: integration-test-results
          path: jmx-metrics/build/reports/tests/integrationTest

  release:
    runs-on: ubuntu-latest
    needs:
      - build
      - integration-test
    steps:
      - run: |
          if [[ $GITHUB_REF_NAME != release/* ]]; then
            echo the release workflow should only be run against release branches
            exit 1
          fi

      - uses: actions/checkout@v3
        with:
          # tags are needed for the generate-release-contributors.sh script
          fetch-depth: 0

      - name: Set up JDK for running Gradle
        uses: actions/setup-java@v3
        with:
          distribution: temurin
          java-version: 17

      - name: Build and publish artifacts
        uses: gradle/gradle-build-action@v2
        with:
          arguments: assemble publishToSonatype closeAndReleaseSonatypeStagingRepository
        env:
          SONATYPE_USER: ${{ secrets.SONATYPE_USER }}
          SONATYPE_KEY: ${{ secrets.SONATYPE_KEY }}
          GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
          GPG_PASSWORD: ${{ secrets.GPG_PASSWORD }}

      - name: Set environment variables
        run: |
          version=$(.github/scripts/get-version.sh)
          if [[ $version =~ ([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
            major="${BASH_REMATCH[1]}"
            minor="${BASH_REMATCH[2]}"
            patch="${BASH_REMATCH[3]}"
          else
            echo "unexpected version: $version"
            exit 1
          fi
          if [[ $patch == 0 ]]; then
            if [[ $minor == 0 ]]; then
              prior_major=$((major - 1))
              prior_minor=$(grep -Po "^## Version $prior_major.\K([0-9]+)" CHANGELOG.md | head -1)
              prior_version="$prior_major.$prior_minor"
            else
              prior_version="$major.$((minor - 1)).0"
            fi
          else
            prior_version="$major.$minor.$((patch - 1))"
          fi
          echo "VERSION=$version" >> $GITHUB_ENV
          echo "PRIOR_VERSION=$prior_version" >> $GITHUB_ENV

      - name: Generate release notes
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          # conditional blocks not indented because of the heredoc
          if [[ $VERSION == *.0 ]]; then
          cat > /tmp/release-notes.txt << EOF
          This release targets the OpenTelemetry SDK $VERSION.

          EOF
          else
          cat > /tmp/release-notes.txt << EOF
          This is a patch release on the previous $PRIOR_VERSION release, fixing the issue(s) below.

          EOF
          fi

          # the complex perl regex is needed because markdown docs render newlines as soft wraps
          # while release notes render them as line breaks
          sed -n "0,/^## Version $VERSION/d;/^## Version /q;p" CHANGELOG.md \
            | perl -0pe 's/(?<!\n)\n *(?!\n)(?![-*] )(?![1-9]+\. )/ /g' \
            >> /tmp/release-notes.txt

          # conditional block not indented because of the heredoc
          if [[ $VERSION == *.0 ]]; then
          cat >> /tmp/release-notes.txt << EOF

          ### 🙇 Thank you
          This release was possible thanks to the following contributors who shared their brilliant ideas and awesome pull requests:

          EOF

          .github/scripts/generate-release-contributors.sh v$PRIOR_VERSION >> /tmp/release-notes.txt
          fi

      - name: Create GitHub release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          cp jmx-metrics/build/libs/opentelemetry-jmx-metrics-$VERSION-alpha.jar opentelemetry-jmx-metrics.jar
          gh release create --target $GITHUB_REF_NAME \
                            --title "Version $VERSION" \
                            --notes-file /tmp/release-notes.txt \
                            --discussion-category announcements \
                            v$VERSION \
                            opentelemetry-jmx-metrics.jar

      - name: Update the change log with the release date
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          date=$(gh release view v$VERSION --json publishedAt --jq .publishedAt | sed 's/T.*//')
          sed -Ei "s/## Version $VERSION .*/## Version $VERSION ($date)/" CHANGELOG.md

      - name: Set git user
        run: .github/scripts/set-git-user.sh

      - name: Create pull request against the release branch
        env:
          # not using the default GITHUB_TOKEN because pull requests generated by it do not run any workflows
          GITHUB_TOKEN: ${{ secrets.BOT_TOKEN }}
        run: |
          message="Add the release date for $VERSION to the change log"
          branch="add-release-date-for-${VERSION}"

          git commit -a -m "$message"
          git push origin HEAD:$branch
          gh pr create --title "[$GITHUB_REF_NAME] $message" \
                       --body "$message." \
                       --head $branch \
                       --base $GITHUB_REF_NAME
