#!/bin/bash
# 快速部署脚本 - 一键构建并部署前端应用
# 使用方法: ./quick-deploy.sh

set -e

SERVER_IP="101.200.208.45"
USERNAME="root"
REMOTE_PATH="/data/www/emotion-museum"
NGINX_CONFIG="/www/server/panel/vhost/nginx/emotion-museum.conf"

echo "=========================================="
echo "🚀 Emotion Museum 前端快速部署"
echo "=========================================="
echo ""

# 步骤 1: 检查 dist 目录
echo "📋 步骤 1: 检查构建目录..."
if [ ! -d "dist" ]; then
    echo "❌ dist 目录不存在，开始构建..."
    npm run build
else
    echo "✅ dist 目录已存在"
fi

# 步骤 2: 构建前端
echo ""
echo "📋 步骤 2: 构建前端应用..."
npm run build
echo "✅ 前端构建完成"

# 步骤 3: 上传文件
echo ""
echo "📋 步骤 3: 上传文件到服务器..."
echo "   服务器: $SERVER_IP"
echo "   目录: $REMOTE_PATH"

if scp dist/index.html "${USERNAME}@${SERVER_IP}:${REMOTE_PATH}/" && \
   scp -r dist/assets "${USERNAME}@${SERVER_IP}:${REMOTE_PATH}/"; then
    echo "✅ 文件上传完成"
else
    echo "❌ 文件上传失败"
    exit 1
fi

# 步骤 4: 验证 Nginx 配置
echo ""
echo "📋 步骤 4: 验证 Nginx 配置..."
if ssh "${USERNAME}@${SERVER_IP}" "nginx -t" > /dev/null 2>&1; then
    echo "✅ Nginx 配置正确"
else
    echo "❌ Nginx 配置有误"
    exit 1
fi

# 步骤 5: 重新加载 Nginx
echo ""
echo "📋 步骤 5: 重新加载 Nginx..."
ssh "${USERNAME}@${SERVER_IP}" "nginx -s reload"
echo "✅ Nginx 已重新加载"

# 步骤 6: 验证部署
echo ""
echo "📋 步骤 6: 验证部署..."
if ssh "${USERNAME}@${SERVER_IP}" "curl -s http://127.0.0.1/emotion-museum/ | grep -q 'DOCTYPE'" > /dev/null 2>&1; then
    echo "✅ 部署验证成功"
else
    echo "⚠️  部署验证失败，请手动检查"
fi

# 完成
echo ""
echo "=========================================="
echo "✅ 部署完成！"
echo "=========================================="
echo ""
echo "📱 访问地址:"
echo "   本地: http://127.0.0.1/emotion-museum/"
echo "   服务器: http://$SERVER_IP/emotion-museum/"
echo ""
echo "📝 后续步骤:"
echo "   1. 在浏览器中访问上述地址"
echo "   2. 清除浏览器缓存（如需要）"
echo "   3. 检查浏览器控制台是否有错误"
echo ""

