name: Sync External Patches

on:
  workflow_dispatch:

permissions:
  contents: write

jobs:
  check_candidates:
    name: Sync External Patches
    runs-on: ubuntu-latest

    steps:
      - name: Check out repository
        uses: actions/checkout@v3

      - name: Setup Python
        uses: actions/setup-python@v5
        # note: This will use the version defined in '.python-version' by defaultç

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version-file: ".nvmrc"

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

      - name: Install requirements
        run: pip3 install -r requirements.txt

      - name: Import external patches
        run: python3 scripts/update_external_patches.py

      - name: Check if any files changed
        id: git-check
        run: |
          if [ -n "$(git status --porcelain)" ]; then
            echo "files_changed=true" >> $GITHUB_OUTPUT
          else
            echo "files_changed=false" >> $GITHUB_OUTPUT
          fi

      - name: Install dependencies
        if: steps.git-check.outputs.files_changed == 'true'
        run: npm ci

      - name: Download Firefox and dependencies
        if: steps.git-check.outputs.files_changed == 'true'
        run: npm run download

      - name: Check if patches got applied
        if: steps.git-check.outputs.files_changed == 'true'
        id: check-patches
        continue-on-error: true
        run: |
          echo "Checking if patches apply cleanly..."
          npm run import

      - name: Create pull request
        uses: peter-evans/create-pull-request@v7
        if: steps.git-check.outputs.files_changed == 'true'
        env:
          GIT_TRACE: 1
          GIT_CURL_VERBOSE: 1
        with:
          token: ${{ secrets.DEPLOY_KEY }}
          commit-message: "chore: Sync external patches"
          branch: "chore/sync-external-patches-${{ github.run_id }}"
          title: "Sync external patches"
          body: |
            This PR syncs the external patches automatically.

            * ${{ steps.check-patches.outcome == 'failure' && '⚠️ Some patches did not apply cleanly. Please review them carefully.' || '✅ All patches applied cleanly.' }}

            @${{ github.actor }} please review and merge this PR. Generated from workflow run [${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}), branch ${{ github.head_ref }}.
          base: dev
          git-token: ${{ secrets.DEPLOY_KEY }}
          delete-branch: true
