#!/bin/bash
set -e
ROOT="$(cd "$(dirname "$0")/.." && pwd)"

echo "=== 1. Building backend ==="
cd "$ROOT/backend"
npm run build
echo ""

echo "=== 2. Stopping backend PM2 to free memory for frontend build ==="
pm2 stop backend
echo ""

echo "=== 3. Building frontend (OOM-safe: max-old-space-size=1024) ==="
cd "$ROOT/frontend"
export NEXT_PUBLIC_API_URL=/api/v1
rm -rf .next
NODE_OPTIONS="--max-old-space-size=1024" npm run build
echo ""

echo "=== 4. Restarting backend PM2 ==="
pm2 restart backend
echo ""

echo "=== 5. Deploying frontend to main site (www.yuzhiran.com) ==="
rm -rf /www/wwwroot/www.yuzhiran.com/_next
cp -r out/* /www/wwwroot/www.yuzhiran.com/
echo ""

echo "=== 6. Deploying frontend to mirror site (www.yuzhiran.com.cn) ==="
rm -rf /www/wwwroot/www.yuzhiran.com.cn/_next
cp -r out/* /www/wwwroot/www.yuzhiran.com.cn/
echo ""

echo "=== 7. Reloading Nginx ==="
nginx -t && nginx -s reload
echo ""

echo "=== Done! ==="
