#!/usr/bin/env bash
# Cache / CDN header probe for app.rangook.ir.
#
# Run it once before a server or CDN change and once after, then diff the two
# outputs. What matters is the "cache-control" line on each object -- if it is
# absent, the browser falls back to heuristic freshness and can hold a
# document for days without ever asking the server.
#
#   bash scripts/cache-probe.sh before > /tmp/before.txt
#   bash scripts/cache-probe.sh after  > /tmp/after.txt
#   diff /tmp/before.txt /tmp/after.txt

HOST="${HOST:-https://app.rangook.ir}"
LABEL="${1:-run}"

# Keep in step with scripts/verify-deploy.sh -- see the note on PROBE_ROUTE
# there for why this is a variable and not a hardcoded path.
PROBE_ROUTE="${PROBE_ROUTE:-/course/detail/}"

echo "################ PROBE: $LABEL"
echo "################ host:  $HOST"
echo "################ utc:   $(date -u +%FT%TZ)"
echo

probe () {
  echo "---- [$2] $1"
  curl -sS -D - -o /dev/null "$HOST$1" \
    | grep -iE "^(HTTP/[0-9.]+ |cache-control:|etag:|last-modified:|age:|x-cache:|cdn-cache:|expires:|content-type:|server:|x-sid:)" \
    | sed 's/\r$//'
  echo
}

probe "/"                      "root-html"
probe "$PROBE_ROUTE"           "course-html"
probe "/home/"                 "home-html"
probe "/version.json"          "version-json"
probe "${PROBE_ROUTE}index.txt" "rsc-payload-txt"

JS=$(curl -sS "$HOST/" | grep -o '/_next/static/[^"?]*\.js' | head -1)
probe "$JS"                    "real-chunk"

echo "---- [missing-chunk] MUST be 404. A 200 + text/html here means the"
echo "     .htaccess rewrite is not being applied, and the browser will try"
echo "     to execute an HTML page as JavaScript."
curl -sS -o /dev/null -w "     status=%{http_code} type=%{content_type} bytes=%{size_download}\n" \
  "$HOST/_next/static/chunks/probe-missing-does-not-exist.js"
echo

echo "---- [query-key] is the query string part of the edge cache key?"
for q in probe-a probe-b; do
  printf "     ?k=%-8s " "$q"
  curl -sS -D - -o /dev/null "$HOST$PROBE_ROUTE?k=$q" \
    | grep -iE "^(x-cache:|age:|x-sid:)" | sed 's/\r$//' | tr '\n' ' '
  echo
done
echo

echo "---- [repeat-hit] same URL 3x -- watch x-cache flip BYPASS/MISS -> HIT"
for i in 1 2 3; do
  printf "     request %s  " "$i"
  curl -sS -D - -o /dev/null "$HOST$PROBE_ROUTE" \
    | grep -iE "^(x-cache:|age:|x-sid:)" | sed 's/\r$//' | tr '\n' ' '
  echo
done
