#!/usr/bin/env bash
# Post-deploy verification. Run this immediately after uploading ./out.
#
# Exists because a deploy can look completely successful while silently
# failing: .htaccess is a dotfile, and most FTP/SFTP clients hide dotfiles by
# default while `scp out/* host:/path` drops them via shell globbing. The
# 2.2.3 .htaccess sat on production through two releases that way, which is
# what left every page with no Cache-Control header at all.
#
#   bash scripts/verify-deploy.sh
#
# Exits non-zero if anything is wrong, so it can gate a release.

HOST="${HOST:-https://app.rangook.ir}"
FAIL=0

# The route used to probe HTML and RSC-payload cache headers. It must be a
# REAL route of the current build.
#
# This used to be hardcoded to /course/view/, and 2.3.2 renamed that route to
# /course/detail/. The probes kept "passing" against the 404 page for a whole
# release: /course/view/ still answered 200 (the catch-all rewrites to /404/),
# still carried text/html, so the Cache-Control assertion below was happily
# checking headers on an error page. A release gate that cannot fail is worse
# than no gate, so check [0] now proves the route exists before anything else
# trusts it.
PROBE_ROUTE="${PROBE_ROUTE:-/course/detail/}"

# Old path -> new path, one pair per retired route. Must match the
# RewriteRules in public/.htaccess; these are what keep clients holding a
# cached copy of an older page from dead-ending on 404.
RETIRED_ROUTES="/course/view/ /course/detail/"

pass () { printf "  \033[32mOK\033[0m   %s\n" "$1"; }
fail () { printf "  \033[31mFAIL\033[0m %s\n" "$1"; FAIL=1; }

hdr () { curl -sS -D - -o /dev/null "$HOST$1" | tr -d '\r'; }

echo "Verifying $HOST"
echo

# 0. The probe route is real. Everything below depends on this.
#
# This used to be hardcoded to /course/view/, and 2.3.2 renamed that route to
# /course/detail/. The probes kept "passing" against the 404 page for a whole
# release: /course/view/ still answered 200 (the catch-all rewrites to /404/)
# and still carried text/html, so the Cache-Control assertions below were
# checking headers on an error page. A release gate that cannot fail is worse
# than no gate.
#
# Detection is by comparing the response against /404/ itself rather than
# looking for a marker in the HTML. The 404 page is a client component behind
# a Suspense boundary, so the EXPORTED html holds only the loading fallback --
# any marker in that component appears after hydration and is never in the
# response body. Comparing bodies needs nothing from the markup: the catch-all
# serves a retired route the identical bytes it serves /404/, and a real route
# always differs (its own chunk references, at minimum).
echo "[0] probe route is a real route"
PROBE_BODY=$(curl -sS "$HOST$PROBE_ROUTE")
NOTFOUND_BODY=$(curl -sS "$HOST/404/")
if [ -z "$PROBE_BODY" ]; then
  fail "$PROBE_ROUTE returned an empty body"
elif [ -z "$NOTFOUND_BODY" ]; then
  fail "/404/ returned an empty body -- cannot tell a real route from the catch-all"
elif [ "$PROBE_BODY" = "$NOTFOUND_BODY" ]; then
  fail "$PROBE_ROUTE is byte-identical to /404/ -- route renamed? update PROBE_ROUTE"
else
  pass "$PROBE_ROUTE is a real route (differs from /404/)"
fi
echo

# 1. The deploy actually landed: what the server serves must match what we built.
echo "[1] build identity"
# Read from ./out, not ./public. generate-version.js rewrites
# public/version.json at the START of every build, so the moment you begin
# preparing the NEXT release it describes a build that exists nowhere yet --
# and this check would report the perfectly good deploy you are standing on as
# a failed upload. ./out/version.json is the artifact that was actually
# shipped. Falls back to public/ only when there is no build directory.
LOCAL_ID=$(node -p "require('./out/version.json').buildId" 2>/dev/null)
if [ -z "$LOCAL_ID" ]; then
  LOCAL_ID=$(node -p "require('./public/version.json').buildId" 2>/dev/null)
fi
LIVE_ID=$(curl -sS "$HOST/version.json?t=$(date +%s)" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).buildId" 2>/dev/null)
if [ -n "$LOCAL_ID" ] && [ "$LOCAL_ID" = "$LIVE_ID" ]; then
  pass "server is serving buildId $LIVE_ID (matches local build)"
else
  fail "buildId mismatch -- local=$LOCAL_ID live=$LIVE_ID (upload did not land?)"
fi
echo

# 2. .htaccess landed: these only pass if the CURRENT .htaccess is live.
echo "[2] .htaccess landed"

# The probe rule is the ONLY check here that proves THIS version of the file
# is live. Everything else in .htaccess shipped in an earlier release, so those
# assertions pass just as happily against a months-old copy -- which is how a
# rule that was never uploaded and a rule that does not work came to look
# identical from the outside. See the DEPLOY PROBE block in public/.htaccess.
PROBE_CODE=$(curl -sS -o /dev/null -w "%{http_code}" "$HOST/__htaccess-probe" --max-time 30)
if [ "$PROBE_CODE" = "302" ]; then
  pass "the CURRENT .htaccess is live (probe redirected)"
else
  fail "probe returned $PROBE_CODE, not 302 -- the server is not running this .htaccess."
  printf "       Two causes, in order of likelihood:
"
  printf "       1. OpenLiteSpeed has not re-read the file. It parses .htaccess
"
  printf "          into memory and keeps those rules until reloaded -- it does
"
  printf "          NOT re-read per request the way Apache does. Do a Graceful
"
  printf "          Restart (aaPanel), or: /usr/local/lsws/bin/lswsctrl restart
"
  printf "       2. The file never uploaded. It is a dotfile, so FTP clients
"
  printf "          hide and skip it silently. rsync -av ./out/ handles it.
"
fi

if hdr "$PROBE_ROUTE" | grep -qiE "^cache-control:.*(no-cache|max-age=0)"; then
  pass "HTML sends Cache-Control: no-cache"
else
  fail "HTML has NO Cache-Control -- browsers will apply heuristic freshness"
fi

MISSING=$(curl -sS -o /dev/null -w "%{http_code}" "$HOST/_next/static/chunks/verify-missing-probe.js")
if [ "$MISSING" = "404" ]; then
  pass "missing _next asset returns a real 404"
else
  fail "missing _next asset returns $MISSING (should be 404; HTML here gets executed as JS)"
fi

MISSING_APK=$(curl -sS -o /dev/null -w "%{http_code}" "$HOST/download/verify-missing-probe.apk")
if [ "$MISSING_APK" = "404" ]; then
  pass "missing download returns a real 404"
else
  fail "missing download returns $MISSING_APK (should be 404; HTML here downloads as a broken APK)"
fi
echo

# 3. Retired routes redirect instead of dead-ending on the 404 page.
#
# A client still holding a cached older page links to the OLD path. Landing
# such a user on 404 is the worst outcome: they got there by tapping a normal
# link, and nothing on the 404 page can tell them why.
echo "[3] retired routes redirect"
set -- $RETIRED_ROUTES
while [ $# -ge 2 ]; do
  OLD="$1"; NEW="$2"; shift 2
  R=$(curl -sS -o /dev/null -w "%{http_code} %{redirect_url}" "$HOST$OLD?id=1")
  CODE=${R%% *}; LOC=${R#* }
  case "$CODE" in
    301|302|307|308)
      case "$LOC" in
        *"$NEW"*)
          case "$LOC" in
            *id=1*) pass "$OLD -> $NEW ($CODE, query preserved)" ;;
            *)      fail "$OLD redirects to $NEW but DROPS the query string (need QSA) -- got $LOC" ;;
          esac ;;
        *) fail "$OLD redirects to $LOC, expected $NEW" ;;
      esac ;;
    *) fail "$OLD returns $CODE, not a redirect -- stale clients dead-end on 404" ;;
  esac
done
echo

# 4. The service worker is reachable.
#
# It is registered as /sw.js?v=<buildId>. If the file is missing the
# registration simply fails and the whole worker layer silently does not
# exist -- documents go back to being served by whatever the browser's HTTP
# cache decides, which is where every version of the stale-app bug has lived.
# Nothing in the UI would show this.
echo "[4] service worker"
SW=$(curl -sS -o /dev/null -w "%{http_code} %{content_type}" "$HOST/sw.js?v=$LOCAL_ID")
SW_CODE=${SW%% *}; SW_TYPE=${SW#* }
if [ "$SW_CODE" = "200" ]; then
  case "$SW_TYPE" in
    *javascript*) pass "sw.js is served as $SW_TYPE" ;;
    *) fail "sw.js served as '$SW_TYPE', not JavaScript -- it will not register" ;;
  esac
else
  fail "sw.js returns $SW_CODE -- the service worker layer will not exist"
fi
echo

# 5. The remaining cache rules.
echo "[5] cache rules"
hdr "/version.json" | grep -qiE "^cache-control:.*(no-store|no-cache|max-age=0)" \
  && pass "version.json always revalidates" \
  || fail "version.json is cacheable -- a stale copy defeats the update check"

hdr "${PROBE_ROUTE}index.txt" | grep -qiE "^cache-control:.*(no-cache|max-age=0)" \
  && pass "RSC .txt payloads always revalidate" \
  || fail "RSC .txt payloads have no no-cache -- stale route content on client navigations"

JS=$(curl -sS "$HOST/" | grep -o '/_next/static/[^"?]*\.js' | head -1)
# Assert the property that matters -- that SOME meaningful cache applies --
# rather than one hardcoded figure. The figure is a policy choice that moves:
# it was 365 days, and was lowered to 1 day in 2.3.5 while the update system
# settles (see deploy/openlitespeed-vhost.conf). Pinning the old number here
# would have turned a deliberate policy change into a red release gate.
#
# The real bug this guards against is NO header at all, which is what happened
# when expiresByType listed application/javascript while OLS serves .js as
# text/javascript. So print the served value and check it is sane.
JS_CC=$(hdr "$JS" | grep -i "^cache-control:" | head -1 | sed 's/^[Cc]ache-[Cc]ontrol: *//')
JS_AGE=$(printf '%s' "$JS_CC" | grep -o 'max-age=[0-9]*' | head -1 | cut -d= -f2)
if printf '%s' "$JS_CC" | grep -qi "immutable"; then
  pass "hashed JS is long-cached ($JS_CC)"
elif [ -n "$JS_AGE" ] && [ "$JS_AGE" -ge 3600 ]; then
  pass "hashed JS cached ${JS_AGE}s (~$((JS_AGE / 3600))h)"
else
  fail "hashed JS cache-control is '${JS_CC:-<none>}' -- check expiresByType covers text/javascript"
fi
echo

# 6. The Android APK the apps are told about (RELEASE.md). Before the first
# Android release there is none, and nothing to check.
echo "[6] android download"
DIRECT_URL=$(curl -sS "$HOST/app-update.json?t=$(date +%s)" | node -p "((JSON.parse(require('fs').readFileSync(0,'utf8')).android || {}).direct || {}).url || ''" 2>/dev/null)
if [ -z "$DIRECT_URL" ]; then
  echo "  --   no direct APK announced in app-update.json yet"
else
  APK=$(curl -sSI -o /dev/null -w "%{http_code} %{content_type}" "$DIRECT_URL")
  APK_CODE=${APK%% *}; APK_TYPE=${APK#* }
  if [ "$APK_CODE" = "200" ] && ! printf '%s' "$APK_TYPE" | grep -qi "text/html"; then
    pass "$DIRECT_URL is served ($APK_TYPE)"
  else
    fail "$DIRECT_URL returns $APK_CODE $APK_TYPE -- out/download/ did not reach the server"
  fi
fi
echo

if [ "$FAIL" = "0" ]; then
  echo "All checks passed."
else
  echo "FAILED -- do not consider this release deployed."
fi
exit $FAIL
