name: Crowdin Sync

on:
  workflow_dispatch:
    inputs:
      locales:
        # Target languages https://developer.crowdin.com/language-codes/
        default: '["en", "fr"]'
        description: "Languages"
        required: true
  schedule: 
    - cron: '30 5,12,17 * * *'
  push:
    branches: [ main ]
    paths:
      - 'en/**'

jobs:

  # ------------------------
  setup:
    name: Setup Params
    runs-on: ubuntu-latest
    outputs:
      locales: ${{ steps.generate-matrix.outputs.locales }}
      branch: ${{ steps.generate-matrix.outputs.branch }}
    steps:
      - name: Generate Matrix
        id: generate-matrix
        run: |
          if [[ ${{ github.event_name == 'workflow_dispatch' }} == true ]]; then
            LOCALES='${{ inputs.locales }}'
          else
            LOCALES='["en", "fr"]'
          fi
          echo "locales=${LOCALES}" >> $GITHUB_OUTPUT       
          echo "branch=${GITHUB_REF##*/}" >> $GITHUB_OUTPUT
          cat $GITHUB_OUTPUT

  crowdin:
    name: Synchronize with Crowdin
    needs:
      - setup    
    runs-on: ubuntu-latest
    permissions: write-all
    env:
      GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
      CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID }}
      CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_MEEDS_APIKEY }}
      BRANCH: ${{ needs.setup.outputs.branch }}
      LOCALES: ${{ needs.setup.outputs.locales }}
    strategy:
      fail-fast: false
      max-parallel: 1 # Should be 1 to avoid parallel builds
      matrix:
        lc: ${{ fromJSON(needs.setup.outputs.locales) }} 
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Matrix
        uses: crowdin/github-action@v1
        with:
          upload_sources: true
          upload_translations: false
          download_translations: true
          commit_message: Sync Crowdin translations - ${{ matrix.lc }}
          localization_branch_name: l10n_${{ env.BRANCH }}_${{ matrix.lc }}
          pull_request_base_branch_name: ${{ env.BRANCH }}
          pull_request_title: New translations - ${{ matrix.lc }} - ${{ env.BRANCH }}
          download_language: ${{ matrix.lc }}

