#!/bin/bash

# 通用 CentOS 优化脚本：替换为阿里云源 + 自动选择最优 DNS（含四川本地 DNS）
# 支持 CentOS 7 / CentOS Stream 8 / CentOS Stream 9
# 作者：AiYun
# 日期：2026-01-21

set -e

COLOR_GREEN='\033[0;32m'
COLOR_YELLOW='\033[1;33m'
COLOR_RED='\033[0;31m'
COLOR_RESET='\033[0m'

log() {
    echo -e "${COLOR_GREEN}[INFO]${COLOR_RESET} $1"
}

warn() {
    echo -e "${COLOR_YELLOW}[WARN]${COLOR_RESET} $1"
}

error() {
    echo -e "${COLOR_RED}[ERROR]${COLOR_RESET} $1" >&2
    exit 1
}

# 检测是否为 root
if [[ $EUID -ne 0 ]]; then
    error "请以 root 用户运行此脚本！"
fi

# 检测系统是否为 CentOS
if ! grep -q "CentOS" /etc/os-release; then
    error "此脚本仅适用于 CentOS 系统！"
fi

# 获取主版本号
if grep -q "CentOS.*7" /etc/redhat-release; then
    OS_VERSION="7"
    PKG_MANAGER="yum"
elif grep -q "CentOS Stream 8" /etc/redhat-release; then
    OS_VERSION="8"
    PKG_MANAGER="dnf"
elif grep -q "CentOS Stream 9" /etc/redhat-release; then
    OS_VERSION="9"
    PKG_MANAGER="dnf"
else
    error "不支持的 CentOS 版本：$(cat /etc/redhat-release)"
fi

log "检测到 CentOS $OS_VERSION，使用 $PKG_MANAGER 包管理器"

# =============== 第一步：备份原 repo 文件 ===============
BACKUP_DIR="/etc/yum.repos.d/backup_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"
log "备份原有 repo 文件到 $BACKUP_DIR"
mv /etc/yum.repos.d/*.repo "$BACKUP_DIR/" 2>/dev/null || warn "无原有 repo 文件，跳过备份"

# =============== 第二步：下载阿里云 repo ===============
log "正在下载阿里云镜像源..."

case $OS_VERSION in
    7)
        curl -s -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
        curl -s -o /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
        ;;
    8)
        curl -s -o /etc/yum.repos.d/CentOS-Stream.repo https://mirrors.aliyun.com/repo/CentOS-Stream.repo
        curl -s -o /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-8.repo
        ;;
    9)
        curl -s -o /etc/yum.repos.d/CentOS-Stream.repo https://mirrors.aliyun.com/repo/CentOS-Stream-9.repo
        curl -s -o /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-9.repo
        ;;
esac

# =============== 第三步：清理并生成缓存 ===============
log "清理并重建包缓存..."
if [ "$PKG_MANAGER" = "yum" ]; then
    yum clean all >/dev/null 2>&1
    yum makecache >/dev/null 2>&1
else
    dnf clean all >/dev/null 2>&1
    dnf makecache >/dev/null 2>&1
fi

# =============== 第四步：自动选择最优 DNS（含四川本地） ===============
log "正在测试公共及四川本地 DNS 延迟..."

# 定义 DNS 列表（含全国 + 四川本地）
declare -A DNS_LIST=(
    # 全国公共 DNS
    ["223.5.5.5"]="AliDNS (阿里)"
    ["114.114.114.114"]="114DNS (中国)"
    ["8.8.8.8"]="Google DNS"
    ["1.1.1.1"]="Cloudflare"
    
    # 四川本地 DNS
    ["202.98.96.68"]="China Telecom Sichuan (成都电信)"
    ["61.139.2.69"]="China Telecom Sichuan (备用)"
    ["211.137.96.20"]="China Mobile Sichuan (四川移动)"
    ["202.101.172.35"]="China Unicom Sichuan (成都联通)"
)

# 安装 bc（用于浮点比较，部分最小化系统可能没有）
if ! command -v bc >/dev/null; then
    log "安装 bc 工具..."
    if [ "$PKG_MANAGER" = "yum" ]; then
        yum install -y bc >/dev/null 2>&1
    else
        dnf install -y bc >/dev/null 2>&1
    fi
fi

best_dns=""
min_latency=9999

for ip in "${!DNS_LIST[@]}"; do
    if command -v ping >/dev/null; then
        avg=$(ping -c 3 -W 2 "$ip" 2>/dev/null | awk -F'/' 'END{print ($5>0)?$5:"9999"}')
        if (( $(echo "$avg < $min_latency" | bc -l) )); then
            min_latency=$avg
            best_dns=$ip
        fi
        log "  $ip (${DNS_LIST[$ip]}) → ${avg}ms"
    else
        warn "未安装 ping，跳过 DNS 测试"
        best_dns="223.5.5.5"
        break
    fi
done

if [ -z "$best_dns" ]; then
    best_dns="202.98.96.68"  # 默认优先四川电信
fi

log "✅ 选择最优 DNS: $best_dns (${DNS_LIST[$best_dns]})"

# 备份原 resolv.conf
RESOLV_CONF="/etc/resolv.conf"
cp "$RESOLV_CONF" "${RESOLV_CONF}.backup_$(date +%Y%m%d_%H%M%S)"

# 写入新 DNS（最优 DNS 优先，其余作为备用）
{
    echo "# Optimized by centos_optimize.sh on $(date)"
    echo "nameserver $best_dns"
    for ip in "${!DNS_LIST[@]}"; do
        [ "$ip" != "$best_dns" ] && echo "nameserver $ip"
    done
} > "$RESOLV_CONF"

# 防止 NetworkManager 覆盖
if systemctl is-active NetworkManager >/dev/null 2>&1; then
    warn "检测到 NetworkManager，建议在网卡配置中设置 DNS 以避免覆盖。"
    warn "例如：在 /etc/sysconfig/network-scripts/ifcfg-* 中添加 PEERDNS=no 和 DNS1=$best_dns"
fi

# =============== 完成 ===============
log "🎉 优化完成！"
log "- YUM/DNF 源已切换为阿里云"
log "- 最优 DNS（含四川本地）已设置为: $best_dns"
log "- 原配置备份路径: $BACKUP_DIR 和 ${RESOLV_CONF}.backup_*"