#!/bin/bash
# =============================================================
#  install_python313.sh
#  在 Ubuntu 上自动安装 Python 3.13 + pip，并配置 python/pip 命令
#  兼容 Ubuntu 22.04+ 的 PEP 668 externally-managed 限制解除
# =============================================================

set -euo pipefail

# ---------- 颜色输出 ----------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

info()    { echo -e "${CYAN}[INFO]${NC}  $*"; }
success() { echo -e "${GREEN}[OK]${NC}    $*"; }
warn()    { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error()   { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }

# ---------- 权限检查 ----------
[[ $EUID -ne 0 ]] && error "请以 root 或 sudo 运行此脚本"

# ---------- 检测系统版本 ----------
if [[ ! -f /etc/os-release ]]; then
    error "无法识别操作系统，仅支持 Ubuntu"
fi
source /etc/os-release
info "检测到系统：$PRETTY_NAME"
[[ "$ID" != "ubuntu" ]] && error "此脚本仅支持 Ubuntu"

# ---------- 1. 添加 deadsnakes PPA 并安装 Python 3.13 ----------
info "更新 apt 软件源..."
apt-get update -qq

info "安装必要依赖..."
apt-get install -y -qq software-properties-common curl

info "添加 deadsnakes PPA（提供 Python 3.13）..."
add-apt-repository -y ppa:deadsnakes/ppa
apt-get update -qq

info "安装 Python 3.13 及相关组件..."
apt-get install -y python3.13 python3.13-venv python3.13-dev

# ---------- 2. 安装 pip for Python 3.13 ----------
info "为 Python 3.13 安装 pip..."
curl -fsSL https://bootstrap.pypa.io/get-pip.py -o /tmp/get-pip.py
python3.13 /tmp/get-pip.py
rm -f /tmp/get-pip.py
success "pip 安装完成"

# ---------- 3. 配置 update-alternatives，映射 python / pip 命令 ----------
info "配置 update-alternatives..."

# python3.13 -> python3 -> python
update-alternatives --install /usr/bin/python3   python3   /usr/bin/python3.13 100
update-alternatives --install /usr/bin/python    python    /usr/bin/python3.13 100

# pip3.13 路径
PIP313=$(python3.13 -m pip --version | awk '{print $NF}' | xargs -I{} find {} -name "pip" -type f 2>/dev/null | head -1)
# 更可靠的方式：直接用 which
PIP_BIN=$(which pip3.13 2>/dev/null || true)

if [[ -n "$PIP_BIN" ]]; then
    update-alternatives --install /usr/bin/pip3 pip3 "$PIP_BIN" 100
    update-alternatives --install /usr/bin/pip  pip  "$PIP_BIN" 100
    success "pip / pip3 已映射到 $PIP_BIN"
else
    # fallback：创建 wrapper 脚本
    warn "未找到 pip3.13 二进制，创建 wrapper 脚本..."
    cat > /usr/local/bin/pip << 'EOF'
#!/bin/bash
python3.13 -m pip "$@"
EOF
    cat > /usr/local/bin/pip3 << 'EOF'
#!/bin/bash
python3.13 -m pip "$@"
EOF
    chmod +x /usr/local/bin/pip /usr/local/bin/pip3
    success "pip / pip3 wrapper 脚本已创建"
fi

# ---------- 4. 解除 PEP 668 externally-managed 限制（Ubuntu 22.04+）----------
#
#  Ubuntu 22.04+ 遵循 PEP 668，在系统 Python 环境中用 pip install 会报错：
#  "error: externally-managed-environment"
#  原因：存在 EXTERNALLY-MANAGED 标记文件，阻止直接向系统环境安装包。
#  解决：删除该标记文件。
#
info "检查并解除 PEP 668 externally-managed 限制..."

MARKER_PATHS=(
    "/usr/lib/python3.13/EXTERNALLY-MANAGED"
    "/usr/lib/python3/dist-packages/EXTERNALLY-MANAGED"
)

REMOVED=0
for marker in "${MARKER_PATHS[@]}"; do
    if [[ -f "$marker" ]]; then
        rm -f "$marker"
        success "已移除：$marker"
        REMOVED=1
    fi
done

# 动态查找其他可能路径
while IFS= read -r -d '' f; do
    rm -f "$f"
    success "已移除：$f"
    REMOVED=1
done < <(find /usr/lib/python3* -maxdepth 1 -name "EXTERNALLY-MANAGED" -print0 2>/dev/null)

if [[ $REMOVED -eq 0 ]]; then
    info "未发现 EXTERNALLY-MANAGED 标记文件（可能系统版本较旧或已处理）"
fi

# ---------- 5. 验证安装 ----------
echo ""
info "========== 安装验证 =========="

PYTHON_VER=$(python --version 2>&1)
PYTHON3_VER=$(python3 --version 2>&1)
PIP_VER=$(pip --version 2>&1)
PIP3_VER=$(pip3 --version 2>&1)

success "python   → $PYTHON_VER"
success "python3  → $PYTHON3_VER"
success "pip      → $PIP_VER"
success "pip3     → $PIP3_VER"

echo ""
success "========== 全部完成 =========="
echo -e "${YELLOW}提示：${NC}如需在当前 Shell 立即生效，请执行：${CYAN}hash -r${NC}"