name: Crowdin Sync

on:
  schedule:
    - cron: '0 0 * * *'

jobs:
  synchronize-with-crowdin:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6
        with:
          ssh-key: ${{ secrets.SSH_PRIVATE_KEY }}
          persist-credentials: true
      - name: push source files
        uses: crowdin/github-action@b4b468cffefb50bdd99dd83e5d2eaeb63c880380 # v2
        with:
          command: 'push'
        env:
          CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID }}
          CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
      - name: pull translations
        uses: crowdin/github-action@b4b468cffefb50bdd99dd83e5d2eaeb63c880380 # v2
        with:
          command: 'download'
          command_args: '--export-only-approved --skip-untranslated-strings'
        env:
          CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID }}
          CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
      - name: Setup Node.js
        uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6
        with:
          node-version-file: frontend/.nvmrc
      - name: Ensure file permissions
        run: |
          find pkg/i18n/lang frontend/src/i18n/lang -type f -name "*.json" -exec sudo chmod 666 {} \;
      - name: Fix exported files
        run: |
          node contrib/clean-translations.js
      - name: Check for changes
        id: check_changes
        run: |
          if git diff --quiet; then
            echo "changes_exist=0" >> "$GITHUB_OUTPUT"
          else
            echo "changes_exist=1" >> "$GITHUB_OUTPUT"
          fi
      - name: Commit files
        if: steps.check_changes.outputs.changes_exist != '0'
        run: |
          git config --local user.email "bot@vikunja.io"
          git config --local user.name "Frederick [Bot]"
          git commit -am "chore(i18n): update translations via Crowdin"
      - name: Push changes
        if: steps.check_changes.outputs.changes_exist != '0'
        uses: ad-m/github-push-action@master
        with:
          ssh: true
          branch: ${{ github.ref }}
