#!/bin/bash

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

# 记录当前目录
pushd .

# 1. 安装gcc
echo -e "${GREEN}安装 gcc...${NC}"
if yum install gcc -y; then
    echo -e "${GREEN}gcc 安装成功！${NC}"
else
    echo -e "${RED}gcc 安装失败！错误信息：$?${NC}"
fi

# 2. 安装Python依赖
dependencies=(
    "zlib zlib-devel"
    "bzip2 bzip2-devel"
    "ncurses ncurses-devel"
    "readline readline-devel"
    "openssl openssl-devel"
    "xz lzma xz-devel"
    "sqlite sqlite-devel"
    "gdbm gdbm-devel"
    "tk tk-devel"
    "mysql-devel"
    "python-devel"
    "libffi-devel"
    "mariadb-devel"
)

for dep in "${dependencies[@]}"; do
    echo -e "${GREEN}安装 $dep...${NC}"
    if yum install $dep -y; then
        echo -e "${GREEN}$dep 安装成功！${NC}"
    else
        echo -e "${RED}$dep 安装失败！错误信息：$?${NC}"
    fi
done

# 3. 前置批量安装
pre_installs=(
    "wget"
    "tar"
    "make"
    "git"
    "epel-release"
    "zbar-devel"
)

for pre in "${pre_installs[@]}"; do
    echo -e "${GREEN}安装 $pre...${NC}"
    if yum install $pre -y; then
        echo -e "${GREEN}$pre 安装成功！${NC}"
    else
        echo -e "${RED}$pre 安装失败！错误信息：$?${NC}"
    fi
done

# 4. 下载 Python 源码
echo -e "${GREEN}下载 Python 3.9.5 源码...${NC}"
if wget --inet4-only http://dw.chan.ink/Python/Python-3.9.5.tgz; then
    echo -e "${GREEN}Python 3.9.5 源码下载成功！${NC}"
else
    echo -e "${RED}Python 3.9.5 源码下载失败！错误信息：$?${NC}"
fi

# 5. 解压源码包
echo -e "${GREEN}解压 Python 3.9.5 源码...${NC}"
if tar -xvf Python-3.9.5.tgz; then
    echo -e "${GREEN}Python 3.9.5 源码解压成功！${NC}"
else
    echo -e "${RED}Python 3.9.5 源码解压失败！错误信息：$?${NC}"
fi

# 6. 编译安装 Python
echo -e "${GREEN}进入 Python 源码目录并开始编译...${NC}"
if cd Python-3.9.5; then
    if ./configure; then
        if make all; then
            if make install; then
                echo -e "${GREEN}Python 3.9.5 编译安装成功！${NC}"
            else
                echo -e "${RED}Python 3.9.5 安装步骤失败！错误信息：$?${NC}"
            fi
        else
            echo -e "${RED}Python 3.9.5 编译 all 步骤失败！错误信息：$?${NC}"
        fi
    else
        echo -e "${RED}Python 3.9.5 配置步骤失败！错误信息：$?${NC}"
    fi
    # 回到初始目录
    popd
else
    echo -e "${RED}进入 Python 源码目录失败！错误信息：$?${NC}"
    # 回到初始目录
    popd
fi

# 7. 测试 Python 安装
echo -e "${GREEN}测试 Python 安装...${NC}"
if python3 --version; then
    echo -e "${GREEN}Python 安装测试成功！${NC}"
else
    echo -e "${RED}Python 安装测试失败！错误信息：$?${NC}"
fi

# 8. 配置 pip 使用阿里云镜像源
echo -e "${GREEN}配置 pip 使用阿里云镜像源...${NC}"
if pip3 config set global.index-url https://mirrors.aliyun.com/pypi/simple/; then
    echo -e "${GREEN}pip 镜像源配置成功！${NC}"
else
    echo -e "${RED}pip 镜像源配置失败！错误信息：$?${NC}"
fi

# 删除无用的压缩包和解压目录
echo -e "${GREEN}删除无用的 Python 压缩包和解压目录...${NC}"
if rm -rf Python-3.9.5.tgz Python-3.9.5; then
    echo -e "${GREEN}Python 压缩包和解压目录删除成功！${NC}"
else
    echo -e "${RED}Python 压缩包和解压目录删除失败！错误信息：$?${NC}"
fi

# 完成
echo -e "${GREEN}Python 3.9.5 安装流程结束！${NC}"
    