#!/bin/bash
# 脚本名称：debian_mirror_huawei_simple.sh
# 功能：仅识别Debian版本，直接全覆盖写入华为云源（无备份、无源类型检测）
# 特性：极致精简、无多余检测、直接替换所有源配置

set -euo pipefail
trap 'echo -e "\033[0;31m❌ 脚本执行出错！\033[0m"' ERR

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 1. 检查root权限
check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        echo -e "${RED}❌ 必须以root权限运行（sudo）！${NC}"
        exit 1
    fi
}

# 2. 仅识别Debian版本（bullseye=11 / bookworm=12）
detect_debian_version() {
    echo -e "${BLUE}🔍 检测Debian版本...${NC}"
    # 优先级：lsb_release > os-release > debian_version > 兜底bookworm
    if command -v lsb_release &>/dev/null; then
        DEBIAN_VERSION=$(lsb_release -cs)
    elif [ -f "/etc/os-release" ]; then
        DEBIAN_VERSION=$(grep -oP 'VERSION="[0-9]+ \(\K\w+' /etc/os-release | head -1)
    elif [ -f "/etc/debian_version" ]; then
        DEB_NUM=$(cut -d '.' -f1 /etc/debian_version)
        DEBIAN_VERSION=$([ "$DEB_NUM" = "11" ] && echo "bullseye" || echo "bookworm")
    else
        DEBIAN_VERSION="bookworm"
    fi
    # 强制兜底，只保留两种有效版本
    DEBIAN_VERSION=$([ "$DEBIAN_VERSION" = "bullseye" ] && echo "bullseye" || echo "bookworm")
    echo -e "${GREEN}✅ 确认版本：Debian $DEBIAN_VERSION${NC}"
}

# 3. 直接全覆盖写入华为云源（不管原有源类型）
write_huawei_mirror() {
    echo -e "${BLUE}🔧 写入华为云源配置...${NC}"
    # 全覆盖替换sources.list（不管原来是什么内容）
    cat > /etc/apt/sources.list << EOF
# 华为云Debian $DEBIAN_VERSION 镜像源（直接全覆盖）
deb https://mirrors.huaweicloud.com/debian/ $DEBIAN_VERSION main contrib non-free non-free-firmware
deb https://mirrors.huaweicloud.com/debian/ $DEBIAN_VERSION-updates main contrib non-free non-free-firmware
deb https://mirrors.huaweicloud.com/debian/ $DEBIAN_VERSION-backports main contrib non-free non-free-firmware
deb https://mirrors.huaweicloud.com/debian-security/ $DEBIAN_VERSION-security main contrib non-free non-free-firmware
EOF

    # 处理Debian12+的debian.sources（直接替换地址）
    if [ -f "/etc/apt/sources.list.d/debian.sources" ]; then
        sed -i 's/deb.debian.org/mirrors.huaweicloud.com/g' /etc/apt/sources.list.d/debian.sources
        echo -e "${GREEN}✅ 同步更新debian.sources文件${NC}"
    fi
    echo -e "${GREEN}✅ 华为云源配置写入完成！${NC}"
}

# 4. 安装HTTPS依赖（容错）+ 验证源
verify_and_complete() {
    echo -e "${BLUE}🔧 安装HTTPS依赖并验证源...${NC}"
    # 安装HTTPS依赖（失败仅提示）
    if ! apt-get install -y --no-install-recommends apt-transport-https ca-certificates &>/dev/null; then
        echo -e "${YELLOW}⚠️  HTTPS依赖安装失败，可稍后手动执行：apt-get install apt-transport-https ca-certificates${NC}"
    fi
    # 更新索引验证源
    if apt-get update -y; then
        echo -e "\n${GREEN}🎉 全部操作完成！华为云源已生效！${NC}"
    else
        echo -e "\n${YELLOW}⚠️  源配置已写入，但APT更新失败！请检查网络后执行：apt-get update${NC}"
    fi
}

# 主流程（极致精简）
main() {
    clear
    echo -e "${BLUE}🎯 Debian华为云源一键替换脚本（极简版）${NC}\n"
    check_root
    detect_debian_version
    echo ""
    write_huawei_mirror
    echo ""
    verify_and_complete
}

# 启动脚本
main