#!/bin/bash

# 1. 安装gcc
echo "安装 gcc..."
if yum install gcc -y; then
    echo "gcc 安装成功！"
else
    echo "gcc 安装失败！错误信息：$?"
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 "安装 $dep..."
    if yum install $dep -y; then
        echo "$dep 安装成功！"
    else
        echo "$dep 安装失败！错误信息：$?"
    fi
done

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

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

# 4. 下载 Python 源码
echo "下载 Python 3.9.5 源码..."
#if wget --inet4-only https://www.python.org/ftp/python/3.9.5/Python-3.9.5.tgz; then
if wget --inet4-only http://dw.chan.ink/Python/Python-3.9.5.tgz; then
    echo "Python 3.9.5 源码下载成功！"
else
    echo "Python 3.9.5 源码下载失败！错误信息：$?"
fi

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

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

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

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

# 完成
echo "Python 3.9.5 安装流程结束！"