#!/bin/bash

# 锡林郭勒盟智慧养殖平台 - 生产环境同步脚本
# 服务器地址: www.jiebanke.com
# 目标目录: /data/nodejs/xlxumu/

SERVER="root@www.jiebanke.com"
TARGET_DIR="/data/nodejs/xlxumu"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}🚀 开始同步文件到生产服务器...${NC}"

# 1. 创建服务器目录结构
echo -e "${YELLOW}📁 创建服务器目录结构...${NC}"
ssh $SERVER "mkdir -p $TARGET_DIR/backend/api"
ssh $SERVER "mkdir -p $TARGET_DIR/backend/database"
ssh $SERVER "mkdir -p $TARGET_DIR/backend/services"
ssh $SERVER "mkdir -p $TARGET_DIR/backend/utils"

# 2. 同步后端API核心文件
echo -e "${YELLOW}📦 同步后端API文件...${NC}"
rsync -avz --delete \
  --include="server.js" \
  --include="package.json" \
  --include="package-lock.json" \
  --include="ai/" \
  --include="data-platform/" \
  --include="farming/" \
  --include="finance/" \
  --include="government/" \
  --include="mall/" \
  --include="trade/" \
  --include="user-center/" \
  --exclude="*" \
  ./backend/api/ $SERVER:$TARGET_DIR/backend/api/

# 3. 同步数据库设计文档
echo -e "${YELLOW}🗄️  同步数据库文档...${NC}"
rsync -avz --delete \
  --include="DESIGN.md" \
  --include="README.md" \
  --exclude="*" \
  ./backend/database/ $SERVER:$TARGET_DIR/backend/database/

# 4. 同步服务层代码
echo -e "${YELLOW}🔧 同步服务层代码...${NC}"
rsync -avz --delete \
  --include="ai-service/" \
  --include="data-platform-service/" \
  --include="farming-service/" \
  --include="finance-service/" \
  --include="government-service/" \
  --include="mall-service/" \
  --include="trade-service/" \
  --include="user-center-service/" \
  --include="README.md" \
  --exclude="*" \
  ./backend/services/ $SERVER:$TARGET_DIR/backend/services/

# 5. 同步工具类
echo -e "${YELLOW}🛠️  同步工具类...${NC}"
rsync -avz --delete \
  --include="README.md" \
  --exclude="*" \
  ./backend/utils/ $SERVER:$TARGET_DIR/backend/utils/

# 6. 创建生产环境配置文件
echo -e "${YELLOW}⚙️  创建生产环境配置...${NC}"
cat > .env.production << EOF
NODE_ENV=production
PORT=3350
DB_HOST=生产环境MySQL地址
DB_PORT=3306
DB_USER=生产环境MySQL用户
DB_PASSWORD=生产环境MySQL密码
DB_NAME=xlxumu_production
JWT_SECRET=your-super-secret-jwt-key-here
EOF

# 上传生产环境配置
scp .env.production $SERVER:$TARGET_DIR/backend/api/.env

# 7. 安装依赖并重启服务
echo -e "${YELLOW}📦 在服务器上安装依赖...${NC}"
ssh $SERVER "cd $TARGET_DIR/backend/api && npm install --production"

echo -e "${YELLOW}🔄 重启PM2服务...${NC}"
ssh $SERVER "cd $TARGET_DIR/backend/api && pm2 delete xlxumu-api 2>/dev/null || true"
ssh $SERVER "cd $TARGET_DIR/backend/api && pm2 start server.js --name xlxumu-api --env production"

# 8. 保存PM2配置
echo -e "${YELLOW}💾 保存PM2配置...${NC}"
ssh $SERVER "pm2 save"

echo -e "${GREEN}✅ 同步完成！${NC}"
echo -e "${GREEN}🌐 API服务地址: https://xlapi.jiebanke.com${NC}"
echo -e "${GREEN}📊 PM2状态: ssh $SERVER 'pm2 status'${NC}"