name: Automatic Backport

on:
  pull_request_target:
    types: [closed]   # fires when PR is closed (merged)

concurrency:
  group: backport-${{ github.workflow }}-${{ github.event.pull_request.number }}
  cancel-in-progress: true

permissions:
  contents: write
  pull-requests: write

jobs:
  backport:
    if: |
      github.event.pull_request.merged == true &&
      contains(github.event.pull_request.labels.*.name, 'backport')
    runs-on: [self-hosted]

    steps:
      # 1. Decide which maintenance branch should receive the back‑port
      - name: Determine target maintenance branch
        id: target
        uses: actions/github-script@v7
        with:
          script: |
            let rel;
            try {
              rel = await github.rest.repos.getLatestRelease({
                owner: context.repo.owner,
                repo: context.repo.repo
              });
            } catch (e) {
              core.setFailed('No existing releases found; cannot determine backport target.');
              return;
            }
            const [maj, min] = rel.data.tag_name.replace(/^v/, '').split('.');
            const branch = `release-${maj}.${min}`;
            core.setOutput('branch', branch);
            console.log(`Latest release ${rel.data.tag_name}; backporting to ${branch}`);
      # 2. Checkout (required by backport‑action)
      - name: Checkout repository
        uses: actions/checkout@v4

      # 3. Create the back‑port pull request
      - name: Create back‑port PR
        uses: korthout/backport-action@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          label_pattern: '' # don't read labels for targets
          target_branches: ${{ steps.target.outputs.branch }}
