name: Sync branches into main

on:
  schedule:
    - cron: "0 14 * * 1"

    - cron: "0 14 * * 3"

  workflow_dispatch:

permissions:
  contents: write
  pull-requests: write

jobs:
  sync:
    runs-on: ubuntu-latest

    steps:
      - name: Determine source branch
        id: branch
        run: |
          DOW=$(date -u +%u)

          if [ "$DOW" = "1" ]; then
            echo "source=laptop" >> "$GITHUB_OUTPUT"
          elif [ "$DOW" = "3" ]; then
            echo "source=desktop" >> "$GITHUB_OUTPUT"
          else
            echo "Not a scheduled sync day"
            exit 1
          fi

      - name: Create pull request
        id: cpr
        uses: peter-evans/create-pull-request@v7
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          base: main
          branch: ${{ steps.branch.outputs.source }}
          title: "Weekly sync: ${{ steps.branch.outputs.source }} → main"
          body: |
            This pull request was created automatically by GitHub Actions.

            If the branch can be merged cleanly, auto-merge will merge it automatically.

            If there are merge conflicts, this PR will remain open until they are resolved.
          draft: false

      - name: Enable auto-merge
        if: steps.cpr.outputs.pull-request-number
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh pr merge \
            ${{ steps.cpr.outputs.pull-request-number }} \
            --auto \
            --merge
