name: upstream-sync

on:
  schedule:
    - cron: "0 3 * * *"
  workflow_dispatch:

jobs:
  sync:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: quattro
          fetch-depth: 0

      - name: Fetch upstream and open sync PR
        env:
          TOKEN: ${{ secrets.GITHUB_TOKEN }}
          API: ${{ github.server_url }}/api/v1
          REPO: ${{ github.repository }}
        run: |
          set -euo pipefail
          git config user.name "omarchycn-sync"
          git config user.email "sync@noreply.git.zacharyzhang.com"
          git remote add upstream https://github.com/basecamp/omarchy.git
          git fetch upstream quattro
          UP=$(git rev-parse upstream/quattro)
          echo "upstream quattro: $UP"
          if git merge-base --is-ancestor "$UP" HEAD; then
            echo "Already up to date with upstream"
            exit 0
          fi
          BR="sync/upstream-${UP:0:8}"
          if git ls-remote --exit-code --heads origin "$BR" > /dev/null; then
            echo "Sync branch $BR already exists, PR pending review"
            exit 0
          fi
          # Trial merge only to report conflict status in the PR body
          MERGE="clean"
          if ! git merge --no-commit --no-ff "upstream/quattro" > /dev/null 2>&1; then
            MERGE="CONFLICTS (resolve manually)"
          fi
          git merge --abort 2> /dev/null || true
          # Branch points at upstream HEAD so the PR always gets created
          git push origin "$UP:refs/heads/$BR"
          curl -sS --fail-with-body -X POST \
            -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
            "$API/repos/$REPO/pulls" \
            -d "{\"base\":\"quattro\",\"head\":\"$BR\",\"title\":\"Sync upstream omarchy ${UP:0:8}\",\"body\":\"Automated sync of basecamp/omarchy quattro @ $UP. Trial merge: $MERGE. Review, run ./test/all, then merge.\"}"
