#!/bin/bash

# Django项目部署汇总脚本
# 按顺序执行现有脚本:
# 1. 创建虚拟环境 (create_venv.sh)
# 2. 生成local_settings.py (generate_local_settings.py)
# 3. 安装项目依赖 (install_requirements.py)
# 4. 迁移数据库和收集静态文件 (makemigrations_migrate_collectstatic.py)
# 5. 配置uWSGI (generate_uwsgi.py)
# 6. 配置Nginx (nginx_config.py)

# ANSI 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m'  # 重置颜色

# 查找项目根目录
find_project_root() {
    local current_dir=$(pwd)
    while true; do
        if [[ -f "$current_dir/manage.py" || -d "$current_dir/.git" ]]; then
            echo "$current_dir"
            return
        fi
        local parent_dir=$(dirname "$current_dir")
        if [[ "$parent_dir" == "$current_dir" ]]; then
            echo "$current_dir"
            return
        fi
        current_dir="$parent_dir"
    done
}

# 获取项目名称
get_project_name() {
    local project_root=$(find_project_root)
    basename "$project_root"
}

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# 获取项目根目录和项目名称（使用新函数）
PROJECT_ROOT=$(find_project_root)
PROJECT_NAME=$(get_project_name)

# 定义虚拟环境路径
VENV_PATH="/envs/${PROJECT_NAME}"

# 显示标题
echo -e "${MAGENTA}============================================${NC}"
echo -e "${MAGENTA}    Django 项目一键部署 - $PROJECT_NAME    ${NC}"
echo -e "${MAGENTA}============================================${NC}"
echo -e "${CYAN}项目根目录: $PROJECT_ROOT${NC}"
echo -e "${CYAN}开始时间: $(date)${NC}"
echo -e "${MAGENTA}============================================${NC}"

# 检查虚拟环境是否存在，不存在则创建
if [ ! -f "$VENV_PATH/bin/activate" ]; then
    echo -e "\n${MAGENTA}================= 步骤 1: 创建虚拟环境 =================${NC}"
    echo -e "${BLUE}执行命令: bash $SCRIPT_DIR/create_venv.sh${NC}"
    
    bash "$SCRIPT_DIR/create_venv.sh"
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ 创建虚拟环境 成功${NC}"
    else
        echo -e "${RED}❌ 创建虚拟环境 失败${NC}"
        echo -e "${RED}部署已中止${NC}"
        exit 1
    fi
else
    echo -e "${GREEN}✅ 虚拟环境已存在: $VENV_PATH${NC}"
fi

# 激活虚拟环境（只激活一次）
echo -e "${YELLOW}正在激活虚拟环境: $VENV_PATH ${NC}"
source "$VENV_PATH/bin/activate"

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ 虚拟环境激活失败${NC}"
    echo -e "${RED}部署已中止${NC}"
    exit 1
fi

echo -e "${GREEN}✅ 虚拟环境已激活${NC}"

# 执行脚本并检查结果
run_step() {
    local step_num=$1
    local step_name=$2
    local command=$3
    
    echo -e "\n${MAGENTA}================= 步骤 $step_num: $step_name =================${NC}"
    echo -e "${BLUE}执行命令: $command${NC}"
    
    # 不再使用子shell，直接在当前shell中执行命令
    eval "$command"
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ $step_name 成功${NC}"
        return 0
    else
        echo -e "${RED}❌ $step_name 失败${NC}"
        
        echo -e "${YELLOW}是否继续执行剩余步骤？(y/n)${NC}"
        read -r continue_exec
        if [[ "$continue_exec" != "y" && "$continue_exec" != "Y" ]]; then
            echo -e "${RED}部署已中止${NC}"
            exit 1
        fi
        
        return 1
    fi
}

# 不再执行创建虚拟环境（已在前面执行）
# 2. 生成local_settings.py
run_step "2" "生成 local_settings.py" "python $SCRIPT_DIR/generate_local_settings_noredis.py"

# 3. 安装项目依赖
run_step "3" "安装项目依赖" "python $SCRIPT_DIR/install_requirements.py"

# 4. 迁移数据库和收集静态文件
run_step "4" "迁移数据库和收集静态文件" "python $SCRIPT_DIR/makemigrations_migrate_collectstatic.py"

# 5. 配置uWSGI
run_step "5" "配置uWSGI" "python $SCRIPT_DIR/generate_uwsgi.py"

# 6. 配置Nginx (如果用户选择)
echo -e "\n${YELLOW}是否配置Nginx? (y/n)${NC}"
read -r config_nginx

if [[ "$config_nginx" == "y" || "$config_nginx" == "Y" ]]; then
    echo -e "\n${MAGENTA}================= 步骤 6: 配置 Nginx =================${NC}"
    
    if [[ $EUID -ne 0 ]]; then
        echo -e "${YELLOW}Nginx配置需要root权限，请输入sudo密码${NC}"
        sudo python "$SCRIPT_DIR/nginx_config.py"
    else
        python "$SCRIPT_DIR/nginx_config.py"
    fi
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ Nginx配置成功${NC}"
    else
        echo -e "${RED}❌ Nginx配置失败${NC}"
    fi
else
    echo -e "${YELLOW}跳过Nginx配置。如需稍后配置，请运行:${NC}"
    echo -e "${YELLOW}sudo python $SCRIPT_DIR/nginx_config.py${NC}"
fi

# 询问是否启动uWSGI
echo -e "\n${YELLOW}是否立即启动uWSGI服务？(y/n)${NC}"
read -r start_uwsgi

if [[ "$start_uwsgi" == "y" || "$start_uwsgi" == "Y" ]]; then
    echo -e "${BLUE}正在启动uWSGI服务...${NC}"
    if [ -f "$PROJECT_ROOT/uwsgi_${PROJECT_NAME}_restart.sh" ]; then
        bash "$PROJECT_ROOT/uwsgi_${PROJECT_NAME}_restart.sh"
        echo -e "${GREEN}✅ uWSGI服务已启动${NC}"
    else
        echo -e "${RED}❌ 找不到uWSGI重启脚本: $PROJECT_ROOT/uwsgi_${PROJECT_NAME}_restart.sh${NC}"
    fi
else
    echo -e "${YELLOW}未启动uWSGI服务。如需稍后启动，请运行:${NC}"
    echo -e "${YELLOW}bash $PROJECT_ROOT/uwsgi_${PROJECT_NAME}_restart.sh${NC}"
fi

# 部署完成
echo -e "\n${MAGENTA}============================================${NC}"
echo -e "${GREEN}🎉 Django项目部署完成！${NC}"
echo -e "${MAGENTA}============================================${NC}"
echo -e "${CYAN}项目名称: $PROJECT_NAME${NC}"
echo -e "${CYAN}完成时间: $(date)${NC}"

echo -e "\n${YELLOW}【管理命令】${NC}"
echo -e "${YELLOW}重启uWSGI: bash $PROJECT_ROOT/uwsgi_${PROJECT_NAME}_restart.sh${NC}"
echo -e "${YELLOW}查看状态: bash $PROJECT_ROOT/uwsgi_${PROJECT_NAME}_status.sh${NC}"
echo -e "${YELLOW}停止服务: bash $PROJECT_ROOT/uwsgi_${PROJECT_NAME}_stop.sh${NC}"
echo -e "${MAGENTA}============================================${NC}"

# 提示用户已经在虚拟环境中
echo -e "\n${GREEN}您当前已在虚拟环境中 (/envs/${PROJECT_NAME})${NC}"
echo -e "${BLUE}💡 提示: 退出环境请输入 'deactivate'${NC}"