name: Sync Cloudflare bulk redirects

on:
  workflow_dispatch:
  push:
    branches: [main]
    paths:
      - "dns/bulk-redirects.json"
      - ".github/workflows/sync-bulk-redirects.yml"

permissions:
  contents: read

jobs:
  sync:
    runs-on: ubuntu-latest
    env:
      CLOUDFLARE_TOKEN: ${{ secrets.CLOUDFLARE_TOKEN || secrets.CLOUDFLARE_DNS_TOKEN || secrets.CLOUDFLARE_API_TOKEN }}
    steps:
      - name: Skip if token missing
        if: env.CLOUDFLARE_TOKEN == ''
        run: echo "CLOUDFLARE_TOKEN not set; skipping sync."

      - name: Checkout
        if: env.CLOUDFLARE_TOKEN != ''
        uses: actions/checkout@v4

      - name: Sync bulk redirects list
        if: env.CLOUDFLARE_TOKEN != ''
        run: |
          if [ -z "$CLOUDFLARE_TOKEN" ]; then
            echo "CLOUDFLARE_TOKEN (or CLOUDFLARE_DNS_TOKEN) is required (scopes: account_filter_lists:edit,account:read)" >&2
            exit 1
          fi

          # Build payload and call Cloudflare API with jq + curl to avoid python heredoc indentation issues
          set -euo pipefail
          echo "Checking dns/bulk-redirects.json"
          jq --version || true
          cat dns/bulk-redirects.json

          account_id=$(jq -r '.account_id // empty' dns/bulk-redirects.json)
          list_name=$(jq -r '.list_name // empty' dns/bulk-redirects.json)
          if [ -z "$account_id" ] || [ -z "$list_name" ]; then
            echo "account_id and list_name are required in dns/bulk-redirects.json" >&2
            exit 1
          fi

          items_payload=$(jq -c '[.items[]? | {redirect: .}]' dns/bulk-redirects.json)

          echo "Finding list id for $list_name in account $account_id"
          lists_resp=$(curl -sS -H "Authorization: Bearer $CLOUDFLARE_TOKEN" "https://api.cloudflare.com/client/v4/accounts/${account_id}/rules/lists")
          list_id=$(echo "$lists_resp" | jq -r --arg NAME "$list_name" '.result[] | select(.name==$NAME) | .id' || true)
          if [ -z "$list_id" ]; then
            echo "List '$list_name' not found in account $account_id" >&2
            echo "API response: $lists_resp" >&2
            exit 1
          fi

          echo "Updating list $list_id with $(echo "$items_payload" | jq 'length') items"
          update_resp=$(curl -sS -X PUT -H "Authorization: Bearer $CLOUDFLARE_TOKEN" -H "Content-Type: application/json" \
            "https://api.cloudflare.com/client/v4/accounts/${account_id}/rules/lists/${list_id}/items" \
            --data "$items_payload")

          echo "Update response:"
          echo "$update_resp" | jq || true

          success=$(echo "$update_resp" | jq -r '.success')
          if [ "$success" != "true" ]; then
            echo "Update failed" >&2
            exit 1
          fi
