name: Prepare plugin for production

on:
  pull_request:
    types:
      - opened
    branches:
      - 'master'

jobs:
  Prepare-Plugin-For-Production:
    if: startsWith(github.head_ref, 'releases/')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Login to Github
        env:
          COMMIT_AUTHOR: ${{ secrets.CI_COMMIT_AUTHOR }}
          COMMIT_EMAIL: ${{ secrets.CI_COMMIT_EMAIL }}
        run: |
          git config --global user.name $COMMIT_AUTHOR
          git config --global user.email $COMMIT_EMAIL

      - uses: mdecoleman/pr-branch-name@1.2.0
        id: vars
        with:
          repo-token: ${{ secrets.GITHUB_TOKEN }}
      - name: Update package.json file
        run: |
          plugin_version=$(echo "${{ steps.vars.outputs.branch }}" | grep -Eo '[0-9].[0-9]+.[0-9]+')
          # we export plugin_version and release branch name as env so we can use them in the next step
          echo "PLUGIN_VERSION=$plugin_version" >> $GITHUB_ENV
          echo "GIT_BRANCH_RELEASE=${{ steps.vars.outputs.branch }}" >> $GITHUB_ENV
          echo "Updating plugin to version $plugin_version"
          npm version $plugin_version
          git push origin HEAD:${{ steps.vars.outputs.branch }} --force
     
      - name: Update CHANGELOG.md
        env:
          JIRA_TOKEN: ${{ secrets.CI_JIRA_TOKEN }}
          JIRA_FIXED_VERSION: "React Native SDK v${{env.PLUGIN_VERSION}}"
        run: |
          chmod +x .github/workflows/scripts/releaseNotesGenerator.sh
          .github/workflows/scripts/releaseNotesGenerator.sh $JIRA_TOKEN "$JIRA_FIXED_VERSION"
          NEW_VERSION_RELEASE_NOTES=$(cat "$JIRA_FIXED_VERSION-releasenotes".txt)
          NEW_VERSION_SECTION="## ${{ env.PLUGIN_VERSION }}\n Release date: *$(date +%F)*\n\n$NEW_VERSION_RELEASE_NOTES\n"
          echo -e "$NEW_VERSION_SECTION\n$(cat CHANGELOG.md)" > CHANGELOG.md
          git add CHANGELOG.md
          git commit -m "Update CHANGELOG.md"
          git push origin HEAD:${{ env.GIT_BRANCH_RELEASE }} --force
