name: Create Sync Action

on:
  pull_request:
    branches:
      - preview 
    types:
      - closed
env: 
  SOURCE_BRANCH_NAME: ${{github.event.pull_request.base.ref}}

jobs:
  create_pr:
    # Only run the job when a PR is merged
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write
      contents: read
    steps:
      - name: Checkout Code
        uses: actions/checkout@v2
        with:
          persist-credentials: false
          fetch-depth: 0

      - name: Setup GH CLI
        run: |
          type -p curl >/dev/null || (sudo apt update && sudo apt install curl -y)
          curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
          sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg
          echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null
          sudo apt update
          sudo apt install gh -y

      - name: Push Changes to Target Repo
        env:
          GH_TOKEN: ${{ secrets.ACCESS_TOKEN }}
        run: |
          TARGET_REPO="${{ secrets.SYNC_TARGET_REPO_NAME }}"
          TARGET_BRANCH="${{ secrets.SYNC_TARGET_BRANCH_NAME }}"
          SOURCE_BRANCH="${{ env.SOURCE_BRANCH_NAME }}"

          git checkout $SOURCE_BRANCH
          git remote add target-origin "https://$GH_TOKEN@github.com/$TARGET_REPO.git"
          git push target-origin $SOURCE_BRANCH:$TARGET_BRANCH