#!/usr/bin/env bash
#
# The cache rule that lets Cloudflare keep the formats dragoman says it may.
#
# A record in a format is served with
# `Cache-Control: public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400`
# — a day in a CDN — and the URL-keyed routes carry no `Vary: Accept`, so
# nothing about them depends on a header a CDN may ignore. Cloudflare still
# answers them `cf-cache-status: DYNAMIC`: it decides what is cacheable by the
# path's extension before it reads the origin's headers, and `/10.1038/
# 171737a0?format=bibtex` has none. Every request therefore reaches the origin
# and converts the record again.
#
# This rule says those paths are eligible, and leaves the length to the origin.
#
# It does NOT cover `/{pid}` itself. That route answers by `Accept` and carries
# `Vary: Accept`; Cloudflare honours `Vary` for `Accept-Encoding` alone, so a
# cached BibTeX body would be served to the next browser asking for the page.
# Only an Enterprise custom cache key can include `Accept`.
#
# Usage:
#   scripts/cloudflare-cache-rule.sh                  # print the rule as JSON
#   CLOUDFLARE_API_TOKEN=… CLOUDFLARE_ZONE_ID=… \
#     scripts/cloudflare-cache-rule.sh --apply        # put it in the zone
#
# The token needs the "Zone / Cache Rules / Edit" permission. --apply replaces
# the zone's http_request_cache_settings ruleset, so a zone that already has
# cache rules wants them added to this one rather than this run over them:
# print the rule, merge it into what `GET /rulesets/phases/
# http_request_cache_settings/entrypoint` returns, and send that.

set -euo pipefail

rule() {
  cat <<'JSON'
{
  "rules": [
    {
      "description": "dragoman: cache the URL-keyed record formats",
      "expression": "(starts_with(http.request.uri.path, \"/dois/\")) or (starts_with(http.request.uri.path, \"/works/\")) or (http.request.uri.query contains \"format=\")",
      "action": "set_cache_settings",
      "action_parameters": {
        "cache": true,
        "edge_ttl": { "mode": "respect_origin" },
        "browser_ttl": { "mode": "respect_origin" },
        "serve_stale": { "disable_stale_while_updating": false }
      }
    }
  ]
}
JSON
}

case "${1:-}" in
  --apply)
    : "${CLOUDFLARE_API_TOKEN:?set CLOUDFLARE_API_TOKEN}"
    : "${CLOUDFLARE_ZONE_ID:?set CLOUDFLARE_ZONE_ID}"
    curl -fsS -X PUT \
      "https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE_ID}/rulesets/phases/http_request_cache_settings/entrypoint" \
      -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
      -H "Content-Type: application/json" \
      --data "$(rule)" |
      python3 -c 'import json,sys; r=json.load(sys.stdin); print("ok" if r.get("success") else json.dumps(r["errors"], indent=2))'
    ;;
  ""|--print)
    rule
    ;;
  *)
    echo "usage: $(basename "$0") [--print|--apply]" >&2
    exit 2
    ;;
esac
