#!/bin/sh
# Post-DNS / post-FE verification — run after PUBLIC_ORIGIN points at this cluster.
set -eu

ROOT="$(cd "$(dirname "$0")" && pwd)"
export CAST_CLUSTER_ROOT="$ROOT"
# shellcheck source=/dev/null
. "$ROOT/scripts/lib/common.sh"
export JOURNAL_ACTOR=verify_global
export JOURNAL_PHASE=verify_global
ensure_shared_mounted

FAIL=0
ORIGIN="${PUBLIC_ORIGIN%/}"

check_url() {
  _path="$1"
  _expect="${2:-200}"
  _url="${ORIGIN}${_path}"
  _action="curl ${_path}"
  journal_start "$_action" "$_url"
  _code="$(curl -sS -o /dev/null -w '%{http_code}' -L --max-time 30 "$_url" 2>/dev/null || echo 000)"
  if [ "$_code" = "$_expect" ]; then
    journal_ok "$_action" "http=${_code}"
    log "OK $_code $_url"
  else
    journal_nok "$_action" "got=${_code} want=${_expect}"
    log "FAIL got $_code want $_expect $_url"
    FAIL=1
  fi
}

journal_start verify_global "origin=${ORIGIN}"
log "verify_global_setup cluster=${CLUSTER_NAME} origin=${ORIGIN}"
[ -n "$ORIGIN" ] || die "set PUBLIC_ORIGIN in cluster.env"

check_url "${APP_HUB_PATH}/" "200"
check_url "${APP_BASE_PATH}/" "200"
check_url "${APP_BASE_PATH}/assets/js/app.js" "200"
check_url "${APP_BASE_PATH}/api/diag.php" "200"

# Short links UI (may redirect to login)
_code="$(curl -sS -o /dev/null -w '%{http_code}' -L --max-time 30 "${ORIGIN}${APP_BASE_PATH}/?view=short_links" 2>/dev/null || echo 000)"
case "$_code" in
  200|302) log "OK $_code short_links" ;;
  *) log "FAIL short_links http=$_code"; FAIL=1 ;;
esac

if [ -n "${FE_PROXY_TARGET:-}" ]; then
  _fe_code="$(curl -sS -o /dev/null -w '%{http_code}' --max-time 15 "http://${FE_PROXY_TARGET}${APP_BASE_PATH}/" 2>/dev/null || echo 000)"
  case "$_fe_code" in
    200|302) log "OK upstream $_fe_code http://${FE_PROXY_TARGET}${APP_BASE_PATH}/" ;;
    *) log "WARN upstream $_fe_code (check FE nginx after DNS cutover)" ;;
  esac
fi

if [ "$FAIL" -eq 0 ]; then
  journal_ok verify_global
  log "verify_global_setup_ok ${CLUSTER_NAME}"
  exit 0
fi
journal_nok verify_global
log "verify_global_setup_FAIL ${CLUSTER_NAME}"
exit 1
