name: Main branch sync
on:
  push:
    branches:
      - main
      - master

jobs:
  synchronize:
    name: Sync main and master
    runs-on: ubuntu-latest
    steps:
      - name: Set up git repository (1)
        uses: actions/checkout@v2
      - name: Set up git repository (2)
        run: |
          # detach HEAD
          git checkout --quiet --detach HEAD
          # fetch main and master branch commits
          git fetch --depth=1 origin main:main master:master
          # fetch commits until main (if main is the old branch)
          git fetch --shallow-since=$(git show -s --format=%ct origin/main)
          # fetch commits until master (if master is the old branch)
          git fetch --shallow-since=$(git show -s --format=%ct origin/master)
      - name: Sync main and master branch
        run: |
          # debug before:
          git log --oneline --decorate --graph --all | head -10; echo

          # if main and master are synced do nothing
          if [[ $(git rev-parse main) = $(git rev-parse master) ]]; then
            return 0
          fi

          # check whether main or master is behind the other
          if git merge-base --is-ancestor main master; then
            # if main is behind master
            git push --force-with-lease origin master:main
          elif git merge-base --is-ancestor master main; then
            # if master is behind main
            git push --force-with-lease origin main:master
          else
            echo "main and master diverged :("
            return 1
          fi

          # debug after:
          git log --oneline --decorate --graph --all | head -10; echo

Add GitHub Action for main-master branch syncing
Add GitHub Action for main-master branch syncing
