#!/bin/bash
# Linux环境部署脚本

set -e

echo "=== 云盘后端Linux部署脚本 ==="

# 检查当前目录
if [ ! -f "main.py" ]; then
    echo "错误: 请在包含main.py的项目根目录下运行此脚本"
    exit 1
fi

# 1. 检查Python环境
echo "1. 检查Python环境..."
if ! command -v python3 &> /dev/null; then
    echo "错误: 未找到python3，请先安装Python 3.8+"
    exit 1
fi
echo "✓ Python版本: $(python3 --version)"

# 2. 创建虚拟环境
echo "2. 创建Python虚拟环境..."
if [ ! -d "venv" ]; then
    echo "正在创建新的虚拟环境..."
    python3 -m venv venv
    echo "✓ 虚拟环境创建成功"
    # 验证虚拟环境文件
    ls -la venv/bin/ | head -5
else
    echo "✓ 虚拟环境已存在"
    # 检查虚拟环境是否完整
    if [ ! -f "venv/bin/activate" ] && [ ! -f "venv/Scripts/activate" ]; then
        echo "⚠ 虚拟环境不完整，正在重新创建..."
        rm -rf venv
        python3 -m venv venv
        echo "✓ 虚拟环境重新创建成功"
    fi
fi

# 3. 激活虚拟环境
echo "3. 激活虚拟环境..."
if [ -f "venv/bin/activate" ]; then
    source venv/bin/activate
    echo "✓ 虚拟环境已激活"
elif [ -f "venv/Scripts/activate" ]; then
    source venv/Scripts/activate
    echo "✓ 虚拟环境已激活 (Windows兼容)"
else
    echo "✗ 虚拟环境激活文件不存在，尝试重新创建虚拟环境..."
    rm -rf venv
    python3 -m venv venv
    if [ -f "venv/bin/activate" ]; then
        source venv/bin/activate
        echo "✓ 虚拟环境重新创建并激活成功"
    else
        echo "✗ 虚拟环境创建失败，请检查Python安装"
        exit 1
    fi
fi

# 4. 升级pip
echo "4. 升级pip..."
pip install --upgrade pip

# 5. 安装依赖
echo "5. 安装Python依赖..."
if [ -f "requirements.txt" ]; then
    pip install -r requirements.txt
    echo "✓ 依赖安装完成"
else
    echo "警告: requirements.txt 不存在，尝试安装基础依赖"
    pip install fastapi uvicorn sqlalchemy pymysql redis python-jose passlib python-multipart pydantic pydantic-settings httpx python-dotenv loguru alembic
fi

# 6. 创建必要目录
echo "6. 创建必要目录..."
mkdir -p logs uploads
echo "✓ 目录创建完成"

# 7. 配置环境变量
echo "7. 配置环境变量..."
if [ ! -f ".env" ]; then
    if [ -f ".env.example" ]; then
        cp .env.example .env
        echo "✓ 已从 .env.example 创建 .env 文件"
        echo "请编辑 .env 文件配置数据库连接等参数"
        echo "编辑命令: nano .env"
    else
        echo "警告: .env.example 不存在，创建默认配置"
        cat > .env << EOF
# 基础配置
ENVIRONMENT=production
DEBUG=false

# 数据库配置
DATABASE_URL=mysql+pymysql://用户名:密码@localhost:3306/数据库名

# Redis配置
REDIS_URL=redis://localhost:6379

# JWT配置
JWT_SECRET_KEY=your-super-secret-jwt-key-change-in-production
JWT_ALGORITHM=HS256
JWT_EXPIRE_MINUTES=30

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

# CORS配置
ALLOWED_HOSTS=["*"]
EOF
        echo "✓ 已创建默认 .env 文件"
    fi
else
    echo "✓ .env 文件已存在"
fi

# 8. 创建启动脚本
echo "8. 创建启动脚本..."
cat > start.sh << 'STARTEOF'
#!/bin/bash
# 云盘后端启动脚本

# 进入脚本所在目录
cd "$(dirname "$0")"

# 激活虚拟环境
if [ -d "venv" ]; then
    source venv/bin/activate
    echo "✓ 虚拟环境已激活"
else
    echo "错误: 虚拟环境不存在，请先运行部署脚本"
    exit 1
fi

# 检查环境文件
if [ ! -f ".env" ]; then
    echo "错误: .env 文件不存在"
    exit 1
fi

# 创建必要目录
mkdir -p logs uploads

# 启动服务
echo "启动云盘后端服务..."
echo "服务地址: http://localhost:8000"
echo "API文档: http://localhost:8000/docs"
echo "按 Ctrl+C 停止服务"
echo ""

python main.py
STARTEOF

chmod +x start.sh
echo "✓ 启动脚本创建完成: start.sh"

# 9. 创建停止脚本
echo "9. 创建停止脚本..."
cat > stop.sh << 'STOPEOF'
#!/bin/bash
# 云盘后端停止脚本

echo "停止云盘后端服务..."
pkill -f "python main.py" || echo "服务未运行"
echo "服务已停止"
STOPEOF

chmod +x stop.sh
echo "✓ 停止脚本创建完成: stop.sh"

# 10. 创建状态检查脚本
echo "10. 创建状态检查脚本..."
cat > status.sh << 'STATUSEOF'
#!/bin/bash
# 云盘后端状态检查脚本

if pgrep -f "python main.py" > /dev/null; then
    echo "✓ 云盘后端服务正在运行"
    echo "进程ID: $(pgrep -f 'python main.py')"
    echo "端口: 8000"
    echo "服务地址: http://localhost:8000"
    echo "API文档: http://localhost:8000/docs"

    # 测试健康检查
    if curl -s http://localhost:8000/api/v1/health > /dev/null; then
        echo "✓ 服务响应正常"
    else
        echo "⚠ 服务运行但可能有问题"
    fi
else
    echo "✗ 云盘后端服务未运行"
    echo "启动服务: ./start.sh"
fi
STATUSEOF

chmod +x status.sh
echo "✓ 状态检查脚本创建完成: status.sh"

# 11. 创建systemd服务（可选）
echo "11. 创建systemd服务..."

# 检查是否为root用户
if [ "$EUID" -eq 0 ]; then
    # root用户创建系统级服务
    SERVICE_FILE="/etc/systemd/system/cloud-drive.service"
    echo "检测到root用户，创建系统级systemd服务..."

    # 检查是否有写入权限
    if [ ! -w "/etc/systemd/system" ]; then
        echo "⚠ 警告: 没有写入/etc/systemd/system的权限，跳过systemd服务创建"
        echo "您可以手动创建服务文件或使用其他管理方式"
    else
        cat > "$SERVICE_FILE" << EOF
[Unit]
Description=Cloud Drive Backend Service
Documentation=https://github.com/your-repo/cloud-drive
After=network.target mysql.service redis.service

[Service]
Type=simple
User=root
WorkingDirectory=$(pwd)
Environment=PATH=$(pwd)/venv/bin
ExecStart=$(pwd)/venv/bin/python $(pwd)/main.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=cloud-drive

# 环境变量
EnvironmentFile=$(pwd)/.env

[Install]
WantedBy=multi-user.target
EOF

        # 重载systemd服务
        systemctl daemon-reload
        echo "✓ 系统级systemd服务已创建"
        echo "启用服务: systemctl enable cloud-drive"
        echo "启动服务: systemctl start cloud-drive"
        echo "查看状态: systemctl status cloud-drive"
        echo "查看日志: journalctl -u cloud-drive -f"
    fi
else
    # 普通用户创建用户级服务
    echo "为普通用户创建systemd用户服务..."

    # 创建用户systemd目录
    USER_SERVICE_DIR="$HOME/.config/systemd/user"

    # 检查并创建目录
    if [ ! -d "$USER_SERVICE_DIR" ]; then
        echo "创建用户systemd目录: $USER_SERVICE_DIR"
        mkdir -p "$USER_SERVICE_DIR" 2>/dev/null || {
            echo "⚠ 无法创建systemd用户目录，尝试使用临时目录..."
            USER_SERVICE_DIR="/tmp/cloud-drive-systemd"
            mkdir -p "$USER_SERVICE_DIR"
            echo "临时目录: $USER_SERVICE_DIR"
        }
    fi

    SERVICE_FILE="$USER_SERVICE_DIR/cloud-drive.service"

    # 检查是否有写入权限
    if [ ! -w "$USER_SERVICE_DIR" ]; then
        echo "⚠ 警告: 没有写入$USER_SERVICE_DIR的权限，尝试修复权限..."
        chmod 755 "$USER_SERVICE_DIR" 2>/dev/null || {
            echo "无法修复权限，尝试使用/tmp目录..."
            USER_SERVICE_DIR="/tmp/cloud-drive-systemd"
            mkdir -p "$USER_SERVICE_DIR"
            SERVICE_FILE="$USER_SERVICE_DIR/cloud-drive.service"
            echo "使用临时目录创建服务文件: $SERVICE_FILE"
        }
    fi

    if [ -w "$USER_SERVICE_DIR" ]; then
        echo "✓ 确认有写入权限: $USER_SERVICE_DIR"
        cat > "$SERVICE_FILE" << EOF
[Unit]
Description=Cloud Drive Backend Service
Documentation=https://github.com/your-repo/cloud-drive
After=network.target

[Service]
Type=simple
WorkingDirectory=$(pwd)
ExecStart=$(pwd)/venv/bin/python $(pwd)/main.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=cloud-drive

[Install]
WantedBy=default.target
EOF

        # 重载systemd用户服务
        systemctl --user daemon-reload 2>/dev/null || echo "⚠ 用户systemd重载失败，可能需要手动重载"
        echo "✓ systemd用户服务已创建"
        echo "启用服务: systemctl --user enable cloud-drive"
        echo "启动服务: systemctl --user start cloud-drive"
        echo "查看状态: systemctl --user status cloud-drive"
        echo "查看日志: journalctl --user -u cloud-drive -f"
    fi
fi

# 创建通用的启动脚本作为备用
echo "创建备用启动脚本..."
cat > systemd_start.sh << 'EOF'
#!/bin/bash
# systemd服务启动脚本

echo "Cloud Drive Backend systemd服务管理"
echo "==================================="
echo ""

if [ "$EUID" -eq 0 ]; then
    echo "系统级服务命令："
    echo "启用服务: systemctl enable cloud-drive"
    echo "启动服务: systemctl start cloud-drive"
    echo "停止服务: systemctl stop cloud-drive"
    echo "重启服务: systemctl restart cloud-drive"
    echo "查看状态: systemctl status cloud-drive"
    echo "查看日志: journalctl -u cloud-drive -f"
else
    echo "用户级服务命令："
    echo "启用服务: systemctl --user enable cloud-drive"
    echo "启动服务: systemctl --user start cloud-drive"
    echo "停止服务: systemctl --user stop cloud-drive"
    echo "重启服务: systemctl --user restart cloud-drive"
    echo "查看状态: systemctl --user status cloud-drive"
    echo "查看日志: journalctl --user -u cloud-drive -f"
fi

echo ""
echo "如果systemd服务不可用，可以使用手动管理："
echo "启动服务: ./start.sh"
echo "停止服务: ./stop.sh"
echo "查看状态: ./status.sh"
EOF

chmod +x systemd_start.sh
echo "✓ 备用启动脚本创建完成: systemd_start.sh"

# 12. 完成提示
echo ""
echo "=== 部署完成 ==="
echo "当前目录: $(pwd)"
echo ""
echo "快速启动方式："
echo "1. 手动启动: ./start.sh"
echo "2. 查看状态: ./status.sh"
echo "3. 停止服务: ./stop.sh"
echo ""
echo "systemd服务方式："
echo "1. 启用服务: systemctl --user enable cloud-drive"
echo "2. 启动服务: systemctl --user start cloud-drive"
echo "3. 查看状态: systemctl --user status cloud-drive"
echo "4. 查看日志: journalctl --user -u cloud-drive -f"
echo ""
echo "访问地址："
echo "- 服务地址: http://localhost:8000"
echo "- API文档: http://localhost:8000/docs"
echo "- 健康检查: http://localhost:8000/api/v1/health"
echo ""
echo "配置文件: .env"
echo "日志目录: logs/"
echo "上传目录: uploads/"
echo ""
echo "注意: 请确保数据库和Redis服务已启动并正确配置"

# 13. 自动启动服务
echo ""
echo "=== 正在启动服务 ==="
echo "启动云盘后端服务..."
./start.sh