# Sync repos
name: sync_on_push

on:
  push:
    branches:
      - 'main'
  workflow_dispatch:

permissions: {}

concurrency:
  group: ${{ github.workflow }}-${{ github.sha }}
  cancel-in-progress: ${{ github.event_name == 'push' }}

jobs:
  sync-repo:
    name: sync_on_push/sync-repo
    if: ${{ github.repository == 'zama-ai/tfhe-rs' }}
    runs-on: ubuntu-latest
    steps:
      - name: git-sync
        env:
          SOURCE_REPO: "zama-ai/tfhe-rs"
          SOURCE_BRANCH: "main"
          DESTINATION_BRANCH: "main"
          USERNAME: ${{ secrets.BOT_USERNAME }}
          TOKEN: ${{ secrets.SYNC_REPO_TOKEN }}
          DEST_REPO: ${{ secrets.SYNC_DEST_REPO }}
        run: |
          echo ">>> Cloning source repo..."
          git lfs install
          git clone "https://${USERNAME}:${TOKEN}@github.com/${SOURCE_REPO}.git" ./tfhe-rs --origin source && cd ./tfhe-rs
          git remote add destination "https://${USERNAME}:${TOKEN}@github.com/${DEST_REPO}.git"

          echo ">>> Fetching all branches references down locally so subsequent commands can see them..."
          git fetch source '+refs/heads/*:refs/heads/*' --update-head-ok

          echo ">>> Print out all branches"
          git --no-pager branch -a -vv

          echo ">>> Fetching all LFS items from source..."
          git lfs fetch --all source "${SOURCE_BRANCH}"

          echo ">>> Pushing git changes..."
          git push destination "${SOURCE_BRANCH}:${DESTINATION_BRANCH}" -f

          echo ">>> Pushing all LFS items..."
          git lfs push --all destination "${DESTINATION_BRANCH}"

      - name: git-sync-tags
        env:
          SOURCE_REPO: "zama-ai/tfhe-rs"
          SOURCE_BRANCH: "refs/tags/*"
          DESTINATION_BRANCH: "refs/tags/*"
          USERNAME: ${{ secrets.BOT_USERNAME }}
          TOKEN: ${{ secrets.SYNC_REPO_TOKEN }}
          DEST_REPO: ${{ secrets.SYNC_DEST_REPO }}
        run: |
          echo ">>> Cloning source repo..."
          git lfs install
          git clone "https://${USERNAME}:${TOKEN}@github.com/${SOURCE_REPO}.git" ./tfhe-rs-tag --origin source && cd ./tfhe-rs-tag
          git remote add destination "https://${USERNAME}:${TOKEN}@github.com/${DEST_REPO}.git"

          echo ">>> Fetching all branches references down locally so subsequent commands can see them..."
          git fetch source '+refs/heads/*:refs/heads/*' --update-head-ok

          echo ">>> Print out all branches"
          git --no-pager branch -a -vv

          echo ">>> Pushing git changes..."
          git push destination "${SOURCE_BRANCH}:${DESTINATION_BRANCH}" -f
