#!/bin/bash

# 保险系统部署脚本
# 用于部署前端和后端到服务器

echo "🚀 开始部署保险系统..."

# 设置变量
PROJECT_ROOT="/var/www/insurance-system"
FRONTEND_DIR="/var/www/insurance-admin-system"
BACKEND_DIR="/var/www/insurance-backend"
NGINX_CONFIG="/etc/nginx/sites-available/ad.ningmuyun.com"

# 1. 创建项目目录
echo "📁 创建项目目录..."
sudo mkdir -p $PROJECT_ROOT
sudo mkdir -p $FRONTEND_DIR
sudo mkdir -p $BACKEND_DIR

# 2. 部署前端
echo "🎨 部署前端..."
cd $FRONTEND_DIR

# 构建前端（如果还没有构建）
if [ ! -d "dist" ]; then
    echo "📦 构建前端项目..."
    npm install
    npm run build
fi

# 设置权限
sudo chown -R www-data:www-data $FRONTEND_DIR/dist
sudo chmod -R 755 $FRONTEND_DIR/dist

# 3. 部署后端
echo "⚙️ 部署后端..."
cd $BACKEND_DIR

# 安装依赖
npm install --production

# 创建环境变量文件
if [ ! -f ".env" ]; then
    echo "📝 创建环境变量文件..."
    cat > .env << EOF
NODE_ENV=production
PORT=3000
FRONTEND_URL=https://ad.ningmuyun.com

# 数据库配置
DB_DIALECT=mysql
DB_HOST=129.211.213.226
DB_PORT=9527
DB_DATABASE=insurance_data
DB_USER=root
DB_PASSWORD=aiotAiot123!

# JWT配置
JWT_SECRET=insurance_super_secret_jwt_key_2024_very_long_and_secure_production
JWT_EXPIRES_IN=24h

# 文件上传配置
UPLOAD_PATH=uploads
MAX_FILE_SIZE=10485760

# 日志配置
LOG_LEVEL=info
EOF
fi

# 4. 配置nginx
echo "🌐 配置nginx..."
sudo cp $BACKEND_DIR/nginx-ad.ningmuyun.com.conf $NGINX_CONFIG

# 启用站点
sudo ln -sf $NGINX_CONFIG /etc/nginx/sites-enabled/

# 测试nginx配置
sudo nginx -t

if [ $? -eq 0 ]; then
    echo "✅ nginx配置测试通过"
    sudo systemctl reload nginx
else
    echo "❌ nginx配置测试失败"
    exit 1
fi

# 5. 配置PM2进程管理
echo "🔄 配置PM2..."
npm install -g pm2

# 创建PM2配置文件
cat > ecosystem.config.js << EOF
module.exports = {
  apps: [{
    name: 'insurance-backend',
    script: 'src/app.js',
    cwd: '$BACKEND_DIR',
    instances: 1,
    exec_mode: 'fork',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    },
    error_file: './logs/err.log',
    out_file: './logs/out.log',
    log_file: './logs/combined.log',
    time: true,
    max_memory_restart: '1G',
    restart_delay: 4000,
    max_restarts: 10,
    min_uptime: '10s'
  }]
};
EOF

# 启动应用
pm2 start ecosystem.config.js
pm2 save
pm2 startup

echo "✅ 部署完成！"
echo "📋 部署信息："
echo "   前端地址: https://ad.ningmuyun.com/insurance/"
echo "   后端API: https://ad.ningmuyun.com/insurance/api/"
echo "   后端端口: 3000"
echo "   进程管理: PM2"

echo "🔍 检查服务状态："
pm2 status
sudo systemctl status nginx
