#!/bin/bash

# 定义颜色代码
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # 无颜色

# 日志记录函数
log() {
    local level=$1
    local message=$2
    local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    case $level in
        "INFO")
            echo -e "${BLUE}[INFO] $timestamp - $message${NC}"
            ;;
        "ERROR")
            echo -e "${RED}[ERROR] $timestamp - $message${NC}"
            ;;
        "WARNING")
            echo -e "${YELLOW}[WARNING] $timestamp - $message${NC}"
            ;;
        "SUCCESS")
            echo -e "${GREEN}[SUCCESS] $timestamp - $message${NC}"
            ;;
        *)
            echo -e "[UNKNOWN] $timestamp - $message"
            ;;
    esac
}

# 安装包函数
install_package() {
    local package=$1
    log "INFO" "安装 $package..."
    if yum install $package -y; then
        log "SUCCESS" "$package 安装成功！"
    else
        log "ERROR" "$package 安装失败！错误信息：$?"
        exit 1
    fi
}

# 下载文件函数（官方源）
download_file() {
    local url=$1
    local filename=$(basename $url)
    log "INFO" "下载 $filename 源码（官方源）..."
    if wget --inet4-only "$url"; then
        log "SUCCESS" "$filename 源码下载成功！"
    else
        log "ERROR" "$filename 源码下载失败！错误信息：$?"
        exit 1
    fi
}

# 解压文件函数
extract_file() {
    local filename=$1
    log "INFO" "解压 $filename 源码..."
    if tar -xvf "$filename"; then
        log "SUCCESS" "$filename 源码解压成功！"
    else
        log "ERROR" "$filename 源码解压失败！错误信息：$?"
        exit 1
    fi
}

# 编译安装 Python 函数
compile_and_install_python() {
    local dir=$1
    log "INFO" "进入 $dir 目录并开始编译..."

    local openssl_prefix="/usr/local/openssl"
    export CFLAGS="-I$openssl_prefix/include"
    export LDFLAGS="-L$openssl_prefix/lib -Wl,-rpath=$openssl_prefix/lib"

    if cd "$dir"; then
        if ./configure \
            --with-openssl="$openssl_prefix" \
            --prefix=/usr/local/python3.9 \
            --enable-shared \
            --with-ensurepip=install; then
            make -j$(nproc) && make install
            log "SUCCESS" "Python 3.9.5 编译安装成功！"
        else
            log "ERROR" "配置或编译失败"
            exit 1
        fi
        cd ..
    else
        log "ERROR" "进入目录失败"
        exit 1
    fi
}

# 配置动态链接库路径
configure_ld_library() {
    local python_lib="/usr/local/python3.9/lib"
    echo "$python_lib" > /etc/ld.so.conf.d/python3.9.conf
    ldconfig
    log "SUCCESS" "动态链接库路径配置完成"
}

# 创建并激活虚拟环境
create_venv() {
    local new_python="/usr/local/python3.9/bin/python3"
    local venv_path="/envs/SemiAutomaticChargeSystem"

    log "INFO" "创建虚拟环境（使用新 Python）..."
    if [ -d "$venv_path" ]; then
        log "WARNING" "虚拟环境已存在，先删除旧环境"
        rm -rf "$venv_path"
    fi

    "$new_python" -m venv "$venv_path" || {
        log "ERROR" "虚拟环境创建失败，请检查新 Python 路径"
        exit 1
    }

    log "INFO" "激活虚拟环境..."
    source "$venv_path/bin/activate"
    log "SUCCESS" "虚拟环境激活成功，当前路径：$venv_path"
}

# 验证环境
verify_environment() {
    log "INFO" "验证 Python 版本..."
    python3 --version | grep -q "3.9.5" || {
        log "ERROR" "虚拟环境未使用新 Python"
        exit 1
    }

    log "INFO" "验证 OpenSSL 版本..."
    local ssl_version=$(python3 -c "import ssl; print(ssl.OPENSSL_VERSION)" 2>&1)
    if [[ ! "$ssl_version" =~ "1.1.1" ]]; then
        log "ERROR" "OpenSSL 版本仍为旧版，请检查编译步骤"
        exit 1
    fi
    log "SUCCESS" "所有环境验证通过！"
}

# 创建系统软链接函数
create_system_symlinks() {
    local python_bin="/usr/local/python3.9/bin"
    local system_bin_dir="/usr/bin"

    log "INFO" "创建系统级软链接，使 python3/pip3 全局可用..."

    # 备份原始Python链接（如果存在）
    if [ -e "$system_bin_dir/python3" ]; then
        mv "$system_bin_dir/python3" "$system_bin_dir/python3.old"
        log "INFO" "已备份原始Python链接: $system_bin_dir/python3.old"
    fi

    if [ -e "$system_bin_dir/pip3" ]; then
        mv "$system_bin_dir/pip3" "$system_bin_dir/pip3.old"
        log "INFO" "已备份原始pip链接: $system_bin_dir/pip3.old"
    fi

    # 创建软链接（-f 强制覆盖，-n 不创建目录链接）
    ln -sfn "$python_bin/python3" "$system_bin_dir/python3"
    ln -sfn "$python_bin/pip3" "$system_bin_dir/pip3"
    log "SUCCESS" "创建软链接成功: python3 -> $python_bin/python3, pip3 -> $python_bin/pip3"
    
    # 验证软链接
    log "INFO" "验证软链接..."
    local new_python_path=$(which python3)
    local new_pip_path=$(which pip3)
    log "INFO" "python3 路径: $new_python_path"
    log "INFO" "pip3 路径: $new_pip_path"
    
    # 验证版本
    log "INFO" "当前Python版本:"
    python3 --version
}

# 更新PATH环境变量
update_path_env() {
    local python_bin="/usr/local/python3.9/bin"
    
    # 更新当前会话的PATH
    export PATH="$python_bin:$PATH"
    log "SUCCESS" "当前会话PATH已更新: $python_bin 已添加"
    
    # 更新系统范围的PATH（/etc/profile.d/）
    cat > /etc/profile.d/python39.sh << EOF
# 添加Python 3.9.5到PATH
export PATH="$python_bin:\$PATH"
EOF
    chmod +x /etc/profile.d/python39.sh
    log "SUCCESS" "已创建系统范围的PATH配置: /etc/profile.d/python39.sh"
    
    # 更新所有用户的bashrc
    if ! grep -q "PATH=\"$python_bin:\$PATH\"" /etc/bashrc; then
        echo -e "\n# Python 3.9.5 PATH" >> /etc/bashrc
        echo "export PATH=\"$python_bin:\$PATH\"" >> /etc/bashrc
        log "SUCCESS" "已更新/etc/bashrc"
    fi
    
    # 加载新配置
    source /etc/profile.d/python39.sh
    
    # 验证PATH
    log "INFO" "当前PATH:"
    echo "$PATH"
    
    # 验证Python命令
    local python_cmd=$(which python3)
    log "INFO" "python3命令位置: $python_cmd"
}

# 配置阿里云加速源
configure_aliyun_mirror() {
    log "INFO" "配置阿里云加速源..."
    mkdir -p ~/.pip
    cat << EOF > ~/.pip/pip.conf
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host = mirrors.aliyun.com
EOF
    log "SUCCESS" "阿里云加速源配置完成"
}

# 主流程
main() {
    # 1. 安装依赖
    log "INFO" "安装编译依赖..."
    install_package "gcc"
    dependencies=(
        "zlib-devel"
        "bzip2-devel"
        "ncurses-devel"
        "readline-devel"
        "openssl-devel"
        "xz-devel"
        "sqlite-devel"
        "gdbm-devel"
        "tk-devel"
        "libffi-devel"
        "libstdc++-devel"
        "zbar-devel"
    )
    for dep in "${dependencies[@]}"; do
        install_package "$dep"
    done

    # 2. 下载并编译 Python
    log "INFO" "下载 Python 源码..."
    download_file "http://dw.chan.ink/Python/Python-3.9.5.tgz"
    extract_file "Python-3.9.5.tgz"
    compile_and_install_python "Python-3.9.5"

    # 3. 配置动态链接库
    configure_ld_library

    # 4. 创建系统软链接
    create_system_symlinks
    
    # 5. 更新PATH环境变量（新增步骤）
    update_path_env

    # 6. 配置阿里云加速源
    configure_aliyun_mirror

    # 7. 环境验证
    verify_environment

    # 8. 清理临时文件
    log "INFO" "清理临时文件..."
    rm -rf Python-3.9.5 Python-3.9.5.tgz
    
    # 9. 总结
    log "SUCCESS" "所有操作完成！Python 3.9.5 已安装并配置"
    log "INFO" "当前Python版本:"
    python3 --version
    log "INFO" "Python路径:"
    which python3
    log "INFO" "请执行以下命令使所有终端生效:"
    echo "source /etc/profile"
}

# 执行主函数
main