---
name: "Purge cdn cache"

on:
  push:
    branches: [master, dev]
    paths:
      - "**/*.sh"
  schedule:
    - cron: "11 22 * * *"
  workflow_dispatch:

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  purge-cache:
    name: "Purge cdn cache"
    runs-on: ubuntu-latest

    steps:
      - name: "Checkout repository"
        uses: actions/checkout@v7
        with:
          fetch-depth: 0

      - name: "Purge script CDN cache"
        if: github.event_name == 'push'
        run: |
          set -eEuo pipefail
          CHANGED_FILES="$(git diff --name-only ${{ github.event.before }} ${{ github.sha }} | grep '\.sh$' || true)"
          [ -n "$CHANGED_FILES" ] || exit 0
          while IFS= read -r CHANGED_FILE; do
            curl -Ls "https://purge.jsdelivr.net/gh/$GITHUB_REPOSITORY@${GITHUB_REF##*/}/$CHANGED_FILE"
          done <<< "$CHANGED_FILES"

      - name: "Purge routing ruleset CDN cache"
        if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
        run: |
          set -eEuo pipefail
          JSDELIVR_URLS="$(grep -EhIor --exclude="*.md" "https://[^\"'\$\\{[:space:];|,]+jsdelivr\.net[^\"'\$\\{[:space:];|,]+(/[^\$\\{[:space:];|,\"']+)+" . | sort -u || true)"
          [ -n "$JSDELIVR_URLS" ] || exit 0
          echo "Purge CDN cache"
          sed 's/https:\/\/[^/]*jsdelivr\.net/https:\/\/purge.jsdelivr.net/' <<< "$JSDELIVR_URLS" | xargs -n 1 curl -Ls -o /dev/null -w "%{http_code} %{url_effective}\n"
          echo "Warming CDN resources"
          while read -r JSDELIVR_URL; do
            curl -Ls -o /dev/null "$JSDELIVR_URL"
            curl -Ls -o /dev/null -w "%{http_code} %{url_effective}\n" "$JSDELIVR_URL"
          done <<< "$JSDELIVR_URLS"
