#!/bin/bash

# 定义颜色代码
GREEN='\033[0;32m'
RED='\033[0;31m'
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 "${GREEN}[INFO] $timestamp - $message${NC}"
            ;;
        "ERROR")
            echo -e "${RED}[ERROR] $timestamp - $message${NC}"
            ;;
        *)
            echo -e "[UNKNOWN] $timestamp - $message"
            ;;
    esac
}

# 安装包函数
install_package() {
    local package=$1
    log "INFO" "安装 $package..."
    if yum install $package -y; then
        log "INFO" "$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 "INFO" "$filename 源码下载成功！"
    else
        log "ERROR" "$filename 源码下载失败！错误信息：$?"
        exit 1
    fi
}

# 解压文件函数
extract_file() {
    local filename=$1
    log "INFO" "解压 $filename 源码..."
    if tar -xvf "$filename"; then
        log "INFO" "$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 "INFO" "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 "INFO" "动态链接库路径配置完成"
}

# 创建并激活虚拟环境
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 "INFO" "虚拟环境激活成功，当前路径：$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 全局可用..."

    # 创建软链接（-f 强制覆盖，-n 不创建目录链接）
    if [ ! -e "$system_bin_dir/python3" ]; then
        ln -sfn "$python_bin/python3" "$system_bin_dir/python3"
        log "INFO" "创建软链接：$system_bin_dir/python3 -> $python_bin/python3"
    else
        log "WARNING" "$system_bin_dir/python3 已存在，跳过创建"
    fi

    if [ ! -e "$system_bin_dir/pip3" ]; then
        ln -sfn "$python_bin/pip3" "$system_bin_dir/pip3"
        log "INFO" "创建软链接：$system_bin_dir/pip3 -> $python_bin/pip3"
    else
        log "WARNING" "$system_bin_dir/pip3 已存在，跳过创建"
    fi
}

# 主流程
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"
    )
    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. 创建并激活虚拟环境
    create_venv

    # 6. 环境验证
    verify_environment

    # 7. 清理临时文件
    log "INFO" "清理临时文件..."
    rm -rf Python-3.9.5 Python-3.9.5.tgz
    log "SUCCESS" "所有操作完成！"
}

# 执行主函数
main    