#!/bin/bash
# 一键切换 DNS 脚本 (支持国内/国外，常用DNS 8~9个)
# 适用于 Linux (Debian/Ubuntu/CentOS/Alpine)

# 定义国内 DNS 列表
DOMESTIC_DNS=(
    "114.114.114.114 # 114DNS"
    "114.114.115.115 # 114DNS 备用"
    "223.5.5.5 # 阿里DNS"
    "223.6.6.6 # 阿里DNS 备用"
    "119.29.29.29 # 腾讯DNS"
    "119.28.28.28 # 腾讯DNS 备用"
    "180.76.76.76 # 百度DNS"
    "240c::6666 # 360DNS (IPv6)"
    "240c::6644 # 360DNS 备用 (IPv6)"
)

# 定义国外 DNS 列表
GLOBAL_DNS=(
    "8.8.8.8 # Google DNS"
    "8.8.4.4 # Google DNS 备用"
    "1.1.1.1 # Cloudflare DNS"
    "1.0.0.1 # Cloudflare DNS 备用"
    "9.9.9.9 # Quad9"
    "149.112.112.112 # Quad9 备用"
    "208.67.222.222 # OpenDNS"
    "208.67.220.220 # OpenDNS 备用"
    "94.140.14.14 # AdGuard"
    "94.140.15.15 # AdGuard 备用"
)

echo "请选择 DNS 类型："
echo "1) 国内 DNS"
echo "2) 国外 DNS"
read -p "请输入选项 [1/2]: " choice

case $choice in
    1)
        echo "可用的国内 DNS："
        i=1
        for dns in "${DOMESTIC_DNS[@]}"; do
            echo "$i) $dns"
            ((i++))
        done
        read -p "请输入选择的序号(可选多个，用空格分隔): " nums
        SELECTED=""
        for num in $nums; do
            ip=$(echo "${DOMESTIC_DNS[$((num-1))]}" | awk '{print $1}')
            [ -n "$ip" ] && SELECTED="$SELECTED\nnameserver $ip"
        done
        ;;
    2)
        echo "可用的国外 DNS："
        i=1
        for dns in "${GLOBAL_DNS[@]}"; do
            echo "$i) $dns"
            ((i++))
        done
        read -p "请输入选择的序号(可选多个，用空格分隔): " nums
        SELECTED=""
        for num in $nums; do
            ip=$(echo "${GLOBAL_DNS[$((num-1))]}" | awk '{print $1}')
            [ -n "$ip" ] && SELECTED="$SELECTED\nnameserver $ip"
        done
        ;;
    *)
        echo "无效选项，退出。"
        exit 1
        ;;
esac

if [ -z "$SELECTED" ]; then
    echo "❌ 没有选择任何有效的 DNS，退出。"
    exit 1
fi

# 备份原 resolv.conf
cp /etc/resolv.conf /etc/resolv.conf.bak.$(date +%s)

# 应用新 DNS
echo -e "$SELECTED" | sed '/^$/d' > /etc/resolv.conf

echo "✅ 已切换 DNS，当前配置："
cat /etc/resolv.conf
echo "原配置已备份在 /etc/resolv.conf.bak.*"
