#!/usr/bin/env bash
# mBlog — post-deploy smoke test. Exits non-zero if anything is unhealthy,
# so it can gate a deploy or trigger a rollback.
# Usage:  ./healthcheck.sh [base-url]      (default: https://mblog.in)
set -uo pipefail

BASE="${1:-${BASE_URL:-https://mblog.in}}"
fail=0

check() { # name  url  expected-substring
  local name="$1" url="$2" want="$3" body code
  if ! body="$(curl -fsS -m 15 -w $'\n%{http_code}' "$url" 2>/dev/null)"; then
    echo "FAIL  $name (request error / non-2xx)"; fail=1; return
  fi
  code="${body##*$'\n'}"
  body="${body%$'\n'*}"
  if [ "$code" = "200" ] && printf '%s' "$body" | grep -q -- "$want"; then
    echo "PASS  $name"
  else
    echo "FAIL  $name (HTTP $code)"; fail=1
  fi
}

echo "Health check against: $BASE"
check "api: categories" "$BASE/api/v1/categories"      '"success":true'
check "api: posts feed"  "$BASE/api/v1/posts?limit=1"   '"success":true'
check "home feed"        "$BASE/"                        '<div class="app"'
check "sitemap"          "$BASE/sitemap.xml"             '<urlset'
check "robots"           "$BASE/robots.txt"              'Sitemap:'
check "admin login"      "$BASE/admin/"                  'mBlog Admin'

echo
if [ "$fail" -eq 0 ]; then
  echo "HEALTHCHECK OK"
else
  echo "HEALTHCHECK FAILED — investigate before finishing the deploy (consider rollback)."
  exit 1
fi
