name: Sync main and master branches

on:
  push:
    branches:
      - main
      - master

jobs:
  sync:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Setup Git
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

      - name: Sync branches
        run: |
          # Get the branch that was pushed to
          PUSHED_BRANCH="${GITHUB_REF#refs/heads/}"

          if [ "$PUSHED_BRANCH" = "main" ]; then
            TARGET_BRANCH="master"
          else
            TARGET_BRANCH="main"
          fi

          echo "Syncing $PUSHED_BRANCH → $TARGET_BRANCH"

          # Fetch all branches
          git fetch origin

          # Check if target branch exists
          if git show-ref --verify --quiet refs/remotes/origin/$TARGET_BRANCH; then
            # Get commit hashes
            PUSHED_COMMIT=$(git rev-parse origin/$PUSHED_BRANCH)
            TARGET_COMMIT=$(git rev-parse origin/$TARGET_BRANCH)

            if [ "$PUSHED_COMMIT" = "$TARGET_COMMIT" ]; then
              echo "Branches are already in sync"
              exit 0
            fi

            echo "Updating $TARGET_BRANCH to match $PUSHED_BRANCH"
            git push origin origin/$PUSHED_BRANCH:refs/heads/$TARGET_BRANCH --force
          else
            echo "Creating $TARGET_BRANCH from $PUSHED_BRANCH"
            git push origin origin/$PUSHED_BRANCH:refs/heads/$TARGET_BRANCH
          fi

          echo "Sync complete!"
