name: Sync stable CHANGELOG to master

on:
  push:
    branches: [stable]
    paths:
      - 'CHANGELOG.md'

jobs:
  merge-changelog:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write

    steps:
      # defaults to `fetch-depth:1` which only checks out the current branch
      # since the action runs on master, it will only checkout master.
      - name: Setup Repository
        uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
        with:
          repository: flutteractionsbot/flutter
          token: ${{ secrets.FLUTTERACTIONSBOT_CP_TOKEN }}
          ref: master

      - name: Configure git
        run: |
          git config user.name "flutteractionsbot"
          git config user.email "<flutter-actions-bot@google.com>"
          git remote add upstream https://github.com/flutter/flutter.git

      # avoid downloading hundreds of other branches/history
      # utilizing `fetch-depth:0` in actions/checkout would clone everything.
      - name: Fetch Stable Branch Only
        run: git fetch upstream stable:stable --depth=1

      - name: Read CHANGELOG.md from the stable branch
        id: read_stable_changelog
        run: |
          # upstream/stable is locally mapped to stable
          # use the local stable ref from above
          CHANGELOG_CONTENT=$(git show stable:CHANGELOG.md)
          echo "CHANGELOG_CONTENT<<EOF" >> $GITHUB_ENV
          echo "$CHANGELOG_CONTENT" >> $GITHUB_ENV
          echo "EOF" >> $GITHUB_ENV

      - name: Prepare PR branch and commit changes
        id: prepare_pr_branch
        env:
          GH_TOKEN: ${{ secrets.FLUTTERACTIONSBOT_CP_TOKEN }}
        run: |
          PR_BRANCH="sync-changelog-stable-to-master-$(date +%s)"
          echo "pr_branch_name=$PR_BRANCH" >> "$GITHUB_OUTPUT"
          git checkout -b "$PR_BRANCH" master
          echo "${{ env.CHANGELOG_CONTENT }}" > CHANGELOG.md
          git add CHANGELOG.md
          git commit -m "Sync CHANGELOG.md from stable"
          git push origin "$PR_BRANCH"

      - name: Create Pull Request
        env:
          GH_TOKEN: ${{ secrets.FLUTTERACTIONSBOT_CP_TOKEN }}
        run: |
          PR_HEAD_BRANCH=${{ steps.prepare_pr_branch.outputs.pr_branch_name }}

          gh pr create \
            --base master \
            --head flutteractionsbot:$PR_HEAD_BRANCH \
            --repo flutter/flutter \
            --title "Sync CHANGELOG.md from stable" \
            --body "This PR automates the synchronization of \`CHANGELOG.md\` from the \`stable\` branch to the \`master\` branch." \
            --label autosubmit
