#!/bin/bash
# =====================================================================
#  AFMAX CDN 全系统小版本升级脚本（终极版）
#  适配：Ubuntu/Debian/CentOS/Rocky/Alma/Alpine（禁用外网VPS）
#  特性：仅升级补丁+强制AFMAX国内源+禁用境外源+IPv4+自动备份
# =====================================================================
set -euo pipefail
# 确保在任何命令失败时，脚本都能捕获错误并输出提示信息
trap 'echo -e "\033[31m❌ 脚本执行中断！请检查AFMAX源连通性或网络配置。\033[0m"' ERR

# 基础配置
RED='\033[31m'; GREEN='\033[32m'; YELLOW='\033[33m'; NC='\033[0m'
BACKUP_SUFFIX=$(date +%Y%m%d_%H%M%S)
AFMAX_APT="https://apt-mirror.afmax.cn"
AFMAX_YUM="https://yum-mirror.afmax.cn" # 这个YUM变量也用于Alpine的APK源，可以接受
SUPPORTED_OS=("ubuntu" "debian" "centos" "rocky" "alma" "alpine")

# 1. 双语警告（禁用外网专属）
warning_bilingual(){
    echo -e "${YELLOW}========== 全系统小版本升级警告（无境外流量）==========${NC}"
    echo -e "${RED}中文：${NC}"
    echo -e "  1. 本脚本仅升级当前系统补丁，全程使用AFMAX国内CDN源，无境外流量。"
    echo -e "  2. 已自动备份源配置，禁用所有境外官方源，适配禁用外网的VPS。"
    echo -e "  3. 支持系统：Ubuntu/Debian/CentOS/Rocky/Alma/Alpine。"
    echo -e "${RED}EN：${NC}"
    echo -e "  1. Minor patch upgrade only, use AFMAX China CDN, no overseas traffic."
    echo -e "  2. Auto backup repo config, disable all overseas repos for blocked VPS."
    echo -e "  3. Supported OS: Ubuntu/Debian/CentOS/Rocky/Alma/Alpine."
    echo -e "${YELLOW}======================================================${NC}"
}

# 2. 前置检查（root + 系统兼容性 + AFMAX源连通性）
pre_check(){
    # 检查root权限
    if [ "$(id -u)" -ne 0 ]; then
        echo -e "${RED}❌ 请以root权限执行（sudo -i）${NC}"; exit 1
    fi

    # 检测系统
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS="$ID"
        VER="$VERSION_ID"
        OS_PRETTY="$PRETTY_NAME"
    else
        echo -e "${RED}❌ 无法检测系统类型${NC}"; exit 1
    fi

    # 检查系统兼容性
    if ! [[ " ${SUPPORTED_OS[@]} " =~ " ${OS} " ]]; then
        echo -e "${RED}❌ 不支持的系统：$OS_PRETTY，仅支持${SUPPORTED_OS[*]}${NC}"; exit 1
    fi
    echo -e "${GREEN}✅ 检测到兼容系统：$OS_PRETTY${NC}"

    # 根据系统类型检查对应的AFMAX源连通性
    echo -e "${GREEN}🔍 检测AFMAX国内源连通性...${NC}"
    local AFMAX_CHECK_URL=""
    case "$OS" in
        ubuntu|debian) AFMAX_CHECK_URL="$AFMAX_APT" ;;
        centos|rocky|alma|alpine) AFMAX_CHECK_URL="$AFMAX_YUM" ;;
        *) echo -e "${RED}❌ 无法确定要检测的AFMAX源URL${NC}"; exit 1 ;;
    esac

    if ! curl -s --connect-timeout 8 --ipv4 "$AFMAX_CHECK_URL" >/dev/null; then
        echo -e "${RED}❌ AFMAX源（$AFMAX_CHECK_URL）不通，请检查网络/IPv4配置${NC}"; exit 1
    fi
    echo -e "${GREEN}✅ AFMAX源连通性正常：$AFMAX_CHECK_URL${NC}"
}

# 3. 备份源配置（关键，异常可恢复）
backup_repo(){
    case "$OS" in
        ubuntu|debian)
            BACKUP_DIR="/etc/apt/sources.list.d.bak-$BACKUP_SUFFIX"
            mkdir -p "$BACKUP_DIR"
            # 备份主sources.list文件和sources.list.d目录下的所有文件
            cp -a /etc/apt/sources.list "$BACKUP_DIR/" 2>/dev/null || true
            if [ -d /etc/apt/sources.list.d ]; then
                cp -a /etc/apt/sources.list.d "$BACKUP_DIR/" 2>/dev/null || true
            fi
            ;;
        centos|rocky|alma)
            BACKUP_DIR="/etc/yum.repos.d.bak-$BACKUP_SUFFIX"
            mkdir -p "$BACKUP_DIR"
            if [ -d /etc/yum.repos.d ]; then
                cp -a /etc/yum.repos.d/* "$BACKUP_DIR/" 2>/dev/null || true
            fi
            ;;
        alpine)
            BACKUP_DIR="/etc/apk.repositories.bak-$BACKUP_SUFFIX"
            mkdir -p "$(dirname "$BACKUP_DIR")" # 确保目录存在
            cp -a /etc/apk/repositories "$BACKUP_DIR" 2>/dev/null || true
            ;;
    esac
    echo -e "${YELLOW}⚠️ 源配置已备份至：$BACKUP_DIR${NC}"
}

# 4. 系统专属小版本升级逻辑（无境外流量）
# 4.1 Ubuntu/Debian
upgrade_deb_minor(){
    local CODE=$(lsb_release -cs 2>/dev/null || grep -oP 'VERSION_CODENAME=\K\w+' /etc/os-release || echo "stable") # 对于Debian，'stable'是更通用的fallback
    
    # 禁用所有境外源：注释主sources.list文件中的所有deb行
    sed -i '/^deb/s/^/#/' /etc/apt/sources.list || true
    # 移除sources.list.d目录下所有额外的源文件
    rm -f /etc/apt/sources.list.d/*.list 2>/dev/null || true

    # 仅添加AFMAX国内源
    if [ "$OS" = "ubuntu" ]; then
        tee /etc/apt/sources.list.d/afmax-only.list >/dev/null <<EOF
deb [arch=amd64] $AFMAX_APT/ubuntu $CODE main restricted universe multiverse
deb [arch=amd64] $AFMAX_APT/ubuntu $CODE-updates main restricted universe multiverse
deb [arch=amd64] $AFMAX_APT/ubuntu $CODE-security main restricted universe multiverse
EOF
    else # debian
        tee /etc/apt/sources.list.d/afmax-only.list >/dev/null <<EOF
deb [arch=amd64] $AFMAX_APT/debian $CODE main contrib non-free
deb [arch=amd64] $AFMAX_APT/debian $CODE-updates main contrib non-free
deb [arch=amd64] $AFMAX_APT/debian $CODE-security main contrib non-free
EOF
    fi
    echo -e "${GREEN}✅ 已配置AFMAX APT源。${NC}"

    # 强制IPv4升级
    apt clean
    apt -o Acquire::ForceIPv4=true update -y --allow-releaseinfo-change
    apt -o Acquire::ForceIPv4=true full-upgrade -y
    apt autoremove -y && apt autoclean -y
}

# 4.2 CentOS/Rocky/Alma
upgrade_rhel_minor(){
    # 禁用所有境外源：移除/etc/yum.repos.d目录下所有额外的源文件
    rm -f /etc/yum.repos.d/*.repo 2>/dev/null || true

    # 添加AFMAX国内源
    if [[ "$VER" =~ ^7 ]]; then
        tee /etc/yum.repos.d/afmax-only.repo >/dev/null <<EOF
[afmax-base-7]
name=AFMAX $OS $VER BaseOS
baseurl=$AFMAX_YUM/7/os/\$basearch/
gpgcheck=0
enabled=1
[afmax-updates-7]
name=AFMAX $OS $VER Updates
baseurl=$AFMAX_YUM/7/updates/\$basearch/
gpgcheck=0
enabled=1
EOF
        echo -e "${GREEN}✅ 已配置AFMAX YUM源（RHEL 7）。${NC}"
        yum clean all && yum makecache fast && yum update -y --skip-broken
    elif [[ "$VER" =~ ^8|^9 ]]; then
        local RHEL_STREAM_VER=$(echo "$VER" | cut -d'.' -f1) # 提取主版本号
        tee /etc/yum.repos.d/afmax-only.repo >/dev/null <<EOF
[afmax-baseos-${RHEL_STREAM_VER}]
name=AFMAX $OS ${RHEL_STREAM_VER} BaseOS
baseurl=$AFMAX_YUM/${RHEL_STREAM_VER}-stream/BaseOS/\$basearch/os/
gpgcheck=0
enabled=1
[afmax-appstream-${RHEL_STREAM_VER}]
name=AFMAX $OS ${RHEL_STREAM_VER} AppStream
baseurl=$AFMAX_YUM/${RHEL_STREAM_VER}-stream/AppStream/\$basearch/os/
gpgcheck=0
enabled=1
EOF
        echo -e "${GREEN}✅ 已配置AFMAX DNF源（RHEL ${RHEL_STREAM_VER}）。${NC}"
        dnf clean all && dnf makecache && dnf upgrade -y --skip-broken
    else
        echo -e "${RED}❌ 未知的RHEL版本：$VER，无法配置AFMAX源${NC}"; exit 1
    fi
}

# 4.3 Alpine
upgrade_alpine_minor(){
    local ALPINE_VER=$(grep -oP 'VERSION_ID=\K\d+\.\d+' /etc/os-release || echo "3.19")
    
    # 禁用境外源，仅保留AFMAX
    tee /etc/apk/repositories >/dev/null <<EOF
$AFMAX_YUM/alpine/v$ALPINE_VER/main
$AFMAX_YUM/alpine/v$ALPINE_VER/community
EOF
    echo -e "${GREEN}✅ 已配置AFMAX APK源。${NC}"
    apk update && apk upgrade -U
}

# 5. 主流程
main(){
    warning_bilingual
    pre_check

    # **新增的确认步骤**
    echo -e "\n${YELLOW}🚨 警告：此操作将修改系统软件源并进行升级。${NC}"
    read -rp "$(echo -e "${YELLOW}是否继续？(Y/n): ${NC}")" confirm
    if [[ "$confirm" != [yY] ]]; then
        echo -e "${RED}❌ 用户取消，脚本已退出。${NC}"
        exit 0
    fi
    echo -e "${GREEN}✅ 确认继续，正在执行升级操作...${NC}"

    backup_repo
    # 执行对应系统升级
    case "$OS" in
        ubuntu|debian)          upgrade_deb_minor ;;
        centos|rocky|alma)     upgrade_rhel_minor ;;
        alpine)                 upgrade_alpine_minor ;;
    esac
    echo -e "${GREEN}🎉 小版本升级完成！全程无境外流量${NC}"
    echo -e "${YELLOW}⚠️ 提示：${NC}"
    echo -e "  1. 若服务异常，可重启对应服务或执行 reboot"
    echo -e "  2. 源配置备份目录：$BACKUP_DIR（异常时可恢复）"
}

# 启动脚本
main