#!/usr/bin/env bash
# Check memory usage and Next.js status (production server).
# Run: sudo bash /var/www/boundary-fastapiandnextjs/scripts/check_memory_nextjs.sh
#
# If Next.js is being killed by OOM (status=9/KILL or exit-code after "memory"):
# - The nextjs.service unit already sets NODE_OPTIONS=--max-old-space-size=512.
# - On 2GB RAM, ensure FastAPI uses 2 workers (gunicorn.conf.py).
# - Optionally lower Next.js heap: edit nextjs.service, set 384, daemon-reload, restart.

set -e
echo "=============================================="
echo "  Memory and Next.js diagnostic"
echo "=============================================="
echo ""
echo "[1] Memory usage (free -h)"
free -h
echo ""
echo "[2] Top memory-consuming processes (ps aux --sort=-%mem | head -20)"
ps aux --sort=-%mem | head -20
echo ""
echo "[3] Next.js service status"
systemctl status nextjs --no-pager || true
echo ""
echo "[4] FastAPI service status (worker count affects RAM)"
systemctl status fastapi --no-pager || true
echo ""
echo "If Next.js is killed by OOM:"
echo "  - 4GB: nextjs.service uses NODE_OPTIONS=--max-old-space-size=1536 and standalone server"
echo "  - 2GB: set 512 and GUNICORN_WORKERS=2. See docs/PRODUCTION_NEXTJS_OOM.md"
echo "  - After editing unit: sudo systemctl daemon-reload && sudo systemctl restart nextjs"
echo "Done."
