name: Sync Public Suffix List

on:
  schedule:
    # Run on the first day of the month at 00:00 UTC
    - cron: '0 0 1 * *'
  workflow_dispatch:

permissions:
  contents: write
  pull-requests: write

jobs:
  sync:
    if: github.repository == 'rspamd/rspamd'
    runs-on: ubuntu-24.04
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Install Perl dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y libnet-idn-encode-perl

      - name: Download public suffix list
        run: |
          curl -sSL https://raw.githubusercontent.com/publicsuffix/list/master/public_suffix_list.dat -o /tmp/public_suffix_list.dat

      - name: Process public suffix list
        run: |
          perl contrib/publicsuffix/idn.pl < /tmp/public_suffix_list.dat > contrib/publicsuffix/effective_tld_names.dat

      - name: Check for changes
        id: check_changes
        run: |
          if git diff --quiet contrib/publicsuffix/effective_tld_names.dat; then
            echo "has_changes=false" >> $GITHUB_OUTPUT
          else
            echo "has_changes=true" >> $GITHUB_OUTPUT
          fi

      - name: Create Pull Request
        if: steps.check_changes.outputs.has_changes == 'true'
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          
          # Delete the branch if it exists (locally and remotely)
          git branch -D sync-public-suffix-list 2>/dev/null || true
          git push origin --delete sync-public-suffix-list 2>/dev/null || true
          
          # Create new branch and commit changes
          git checkout -b sync-public-suffix-list
          git add contrib/publicsuffix/effective_tld_names.dat
          git commit -m "[Minor] Update public suffix list"
          git push origin sync-public-suffix-list
          
          # Create PR
          gh pr create \
            --title "Update public suffix list" \
            --body "This PR updates the public suffix list from https://github.com/publicsuffix/list. This is an automated update generated by the sync workflow." \
            --base master \
            --head sync-public-suffix-list
        env:
          GH_TOKEN: ${{ github.token }}
