name: Sync Beta from Master

# Merges master into beta after every push to master so beta never falls
# behind.  Uses RELEASE_TOKEN (admin user) which can push to protected
# branches, same as the CHANGELOG commit in auto-tag.yml.
#
# NOTE: commits carrying [skip ci] in their message (e.g. the CHANGELOG
# commit from auto-tag.yml) suppress all workflow runs, so this job will
# not fire for those specific commits.  The NEXT real push to master will
# bring the skipped commit(s) along in the merge.  If you need immediate
# sync of every commit, remove [skip ci] from auto-tag.yml's CHANGELOG
# commit and instead gate auto-tag.yml with a path or branch filter.

on:
  push:
    branches:
      - master

concurrency:
  group: sync-beta
  cancel-in-progress: true

jobs:
  sync:
    runs-on: linux-amd64
    container:
      image: alpine:latest
    steps:
      - name: Merge master into beta
        env:
          RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
        run: |
          set -eu
          apk add --no-cache git

          git init
          git remote add origin \
            "http://oauth2:${RELEASE_TOKEN}@172.0.0.29:3000/${GITHUB_REPOSITORY}.git"
          git config user.name "gitea-actions[bot]"
          git config user.email "gitea-actions@local"

          # Check beta exists before trying to merge into it
          if ! git ls-remote --exit-code origin refs/heads/beta >/dev/null 2>&1; then
            echo "beta branch does not exist yet — skipping sync"
            exit 0
          fi

          git fetch origin master beta
          git checkout -b beta origin/beta

          # If beta already contains everything in master (e.g. right after a
          # beta→master promotion) there is nothing to do.
          if git merge-base --is-ancestor origin/master HEAD; then
            echo "beta is already up to date with master — nothing to do"
            exit 0
          fi

          if git merge --no-ff origin/master \
               -m "chore: sync beta from master [skip ci]"; then
            git push origin beta
            echo "✓ beta synced with master"
          else
            echo "✗ Merge conflict — manual resolution required"
            git merge --abort || true
            exit 1
          fi
