# Copyright (C) 2025 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

name: Merge main to canary

on:
  workflow_dispatch:  # Manual trigger via GitHub UI button

permissions:
  contents: write  # Required to push branch
  pull-requests: write  # Required to create PR

jobs:
  merge-main-to-canary:
    runs-on: ubuntu-latest
    environment: canary
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          ref: canary
          fetch-depth: 0  # Full history needed for merge

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

      - name: Fetch origin/main
        run: git fetch origin main

      - name: Create merge branch
        run: |
          BRANCH_NAME="dev/github-actions/merge-main-to-canary-$(date +%Y%m%d-%H%M%S)"
          echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
          git checkout -b "$BRANCH_NAME"

      - name: Merge main into branch (replace tree with main)
        run: |
          git merge -s ours origin/main --no-commit
          git read-tree -m -u origin/main
          git commit -m "Merge main into canary (automated)"

      - name: Push branch and create PR
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          git push origin "$BRANCH_NAME"
          gh pr create \
            --base canary \
            --head "$BRANCH_NAME" \
            --title "Merge main into canary (automated)" \
            --body "Automated PR to merge main into canary."
