#!/bin/bash

# Government Backend 部署脚本
# 用于自动化部署 government-backend 服务

set -e

echo "🚀 开始部署 Government Backend..."

# 1. 检查环境
echo "📋 检查环境..."
if ! command -v node &> /dev/null; then
    echo "❌ Node.js 未安装"
    exit 1
fi

if ! command -v npm &> /dev/null; then
    echo "❌ npm 未安装"
    exit 1
fi

if ! command -v pm2 &> /dev/null; then
    echo "📦 安装 PM2..."
    npm install -g pm2
fi

# 2. 进入项目目录
PROJECT_DIR="/var/www/government-backend"
if [ ! -d "$PROJECT_DIR" ]; then
    echo "❌ 项目目录不存在: $PROJECT_DIR"
    exit 1
fi

cd $PROJECT_DIR

# 3. 更新代码
echo "📥 更新代码..."
git pull origin main

# 4. 安装依赖
echo "📦 安装依赖..."
npm install --production

# 5. 创建日志目录
echo "📁 创建日志目录..."
mkdir -p logs

# 6. 检查配置文件
if [ ! -f ".env" ]; then
    echo "⚠️  .env 文件不存在，创建默认配置..."
    cat > .env << EOF
NODE_ENV=production
PORT=5352
DB_DIALECT=mysql
DB_HOST=129.211.213.226
DB_PORT=9527
DB_DATABASE=ningxia_zhengfu
DB_USER=root
DB_PASSWORD=aiotAiot123!
JWT_SECRET=government_super_secret_jwt_key_2024_very_long_and_secure
LOG_LEVEL=info
CORS_ORIGIN=*
UPLOAD_PATH=./uploads
MAX_FILE_SIZE=10485760
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
EOF
fi

# 7. 停止现有进程
echo "🛑 停止现有进程..."
pm2 stop government-backend 2>/dev/null || true
pm2 delete government-backend 2>/dev/null || true

# 8. 启动服务
echo "🚀 启动服务..."
pm2 start ecosystem.config.js --env production

# 9. 保存PM2配置
echo "💾 保存PM2配置..."
pm2 save

# 10. 设置开机自启
echo "🔄 设置开机自启..."
pm2 startup

# 11. 检查服务状态
echo "✅ 检查服务状态..."
sleep 3
pm2 status

echo ""
echo "🎉 部署完成！"
echo "📊 服务状态: pm2 status"
echo "📝 查看日志: pm2 logs government-backend"
echo "🔍 监控面板: pm2 monit"
echo "🌐 服务地址: http://localhost:5352"