#!/bin/bash
################################################################################
# 自動設置 DNS 腳本 (增強版) - 支持 IPv4/IPv6/双栈
################################################################################
# 版權所有 (C) 2020-2026 程星博客
# 官方網站：https://www.程星.top/
# 作者 B 站：https://space.bilibili.com/1765875510
# QQ 粉絲群：810288129
# 
# 【功能特性】
# ✓ 支持 IPv4/IPv6/双栈 三种网络模式
# ✓ 支持 50+ 个国内外 DNS 服务器
# ✓ 支持 DNS 速度自动测试
# ✓ 支持交互式键盘选择
# ✓ 支持多语言（简体中文/繁体中文/English）
# ✓ 支持 Tailscale 检测与处理
# ✓ 支持多种网络管理方式（Netplan/NetworkManager/systemd-resolved 等）
# ✓ 支持 DNS 配置验证
# ✓ 支持配置备份与恢复
#
# 【贊助商】
# 千問 AI：https://tongyi.aliyun.com/qianwen - 阿里巴巴通義千問大模型
# 轉轉二手：https://www.zhuanzhuan.com - 專業二手交易平臺
#
# 【使用說明】
# 1. 下載腳本：curl -o dnsxg.sh https://xz.xn--kiv765b.top/dnsxg.sh
# 2. 添加執行權限：chmod +x dnsxg.sh
# 3. 以 root 身份運行：sudo ./dnsxg.sh
#
# 【版本信息】
# 版本號：v3.0.0
# 更新日期：2026-02-21
# 支持系統：Debian/Ubuntu/CentOS/RHEL/Fedora/Arch 等主流 Linux 發行版
################################################################################

set -o pipefail

# ==================== 顏色定義 ====================
# 檢測終端是否支持顏色，不支持則禁用所有顏色代碼
if [[ -t 1 ]]; then
    # 基本顏色
    RED='\e[0;31m'
    GREEN='\e[0;32m'
    YELLOW='\e[0;33m'
    BLUE='\e[0;34m'
    CYAN='\e[0;36m'
    MAGENTA='\e[0;35m'
    WHITE='\e[0;37m'
    GRAY='\e[0;90m'
    
    # 粗體顏色
    BOLD_RED='\e[1;31m'
    BOLD_GREEN='\e[1;32m'
    BOLD_YELLOW='\e[1;33m'
    BOLD_BLUE='\e[1;34m'
    BOLD_CYAN='\e[1;36m'
    BOLD_MAGENTA='\e[1;35m'
    BOLD_WHITE='\e[1;37m'
    
    # 背景顏色
    BG_RED='\e[41m'
    BG_GREEN='\e[42m'
    BG_YELLOW='\e[43m'
    BG_BLUE='\e[44m'
    
    # 重置
    NC='\e[0m'
    BOLD='\e[1m'
    DIM='\e[2m'
    UNDERLINE='\e[4m'
    BLINK='\e[5m'
    REVERSE='\e[7m'
else
    # 終端不支持顏色，所有顏色變量設為空
    RED="" GREEN="" YELLOW="" BLUE="" CYAN="" MAGENTA="" WHITE="" GRAY=""
    BOLD_RED="" BOLD_GREEN="" BOLD_YELLOW="" BOLD_BLUE="" BOLD_CYAN="" BOLD_MAGENTA="" BOLD_WHITE=""
    BG_RED="" BG_GREEN="" BG_YELLOW="" BG_BLUE=""
    NC="" BOLD="" DIM="" UNDERLINE="" BLINK="" REVERSE=""
fi

# ==================== 全局變量 ====================
# DNS 選擇相關
SELECTED_DNS=""
SELECTED_DNS_NAME=""
SELECTED_INDEX=0
SELECTED_DNS_TYPE="standard"
TEST_DOMAIN="www.baidu.com"
declare -a DNS_SPEED_RESULTS
FASTEST_INDEX=0
CURRENT_PAGE=1
CURRENT_SELECTION=0

# 語言與界面
CURRENT_LANG="zh_CN"
NETWORK_MANAGER=""
INTERFACE=""
SKIP_TEST=0
SCRIPT_VERSION="3.0.0"

# 服務器信息
SERVER_IP=""
SERVER_LOCATION=""
SERVER_ISP=""
IPV4_SUPPORTED=0
IPV6_SUPPORTED=0
IP_MODE=""  # ipv4, ipv6, dual

# Tailscale 檢測
TAILSCALE_ACTIVE=0

# DNS 測試配置
DNS_TEST_TIMEOUT=0.5
DNS_TEST_COUNT=3

# 配置備份
BACKUP_DIR="/root/dns_backup"
BACKUP_CREATED=0

# 進程 ID（用於清理）
LISTEN_PID=""

# ==================== 作者信息 ====================
show_author_info() {
    clear
    echo ""
    echo -e "${WHITE}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${BOLD_MAGENTA}╔════════════════════════════════════════════╗${NC}        ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${BOLD_MAGENTA}║${NC}                                        ${BOLD_MAGENTA}║${NC}        ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${BOLD_MAGENTA}║${NC}   ${BOLD_WHITE}📺 自動設置 DNS 腳本 (增強版) v${SCRIPT_VERSION}${NC}   ${BOLD_MAGENTA}║${NC}        ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${BOLD_MAGENTA}║${NC}                                        ${BOLD_MAGENTA}║${NC}        ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${BOLD_MAGENTA}╚════════════════════════════════════════════╝${NC}        ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${MAGENTA}📺 作者：程星${NC}                                          ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${RED}🎬 B 站${NC}: space.bilibili.com/1765875510                  ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${RED}👤 UID${NC}: 1765875510                                     ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${CYAN}📱 抖音/YouTube/TikTok${NC}: 是程星哒                    ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${GREEN}💬 QQ 粉絲群${NC}: 810288129                               ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${BLUE}🌐 官網${NC}: https://www.程星.top/                       ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
    echo -e "${WHITE}╠══════════════════════════════════════════════════════════════╣${NC}"
    echo -e "${WHITE}║${NC}        ${YELLOW}🤖 千問 AI${NC}: https://tongyi.aliyun.com/qianwen          ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${GREEN}🔄 轉轉二手${NC}: https://www.zhuanzhuan.com               ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
    echo -e "${WHITE}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

show_sponsor_banner() {
    echo ""
    echo -e "${WHITE}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${WHITE}║${NC}              ${BOLD_YELLOW}⭐ 感謝贊助商支持 ⭐${NC}                          ${WHITE}║${NC}"
    echo -e "${WHITE}╠══════════════════════════════════════════════════════════════╣${NC}"
    echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}  ${BOLD_MAGENTA}🤖 千問 AI${NC} - 阿里巴巴通義千問大模型                        ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}     ${CYAN}https://tongyi.aliyun.com/qianwen${NC}                              ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}     強大的 AI 助手，支持對話、寫作、編程、分析等功能                ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}  ${BOLD_GREEN}🔄 轉轉二手${NC} - 專業二手交易平臺                              ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}     ${CYAN}https://www.zhuanzhuan.com${NC}                                     ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}     手機數碼、奢侈品、圖書等二手交易，官方驗更放心                  ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
    echo -e "${WHITE}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

show_author_end() {
    echo ""
    echo -e "${WHITE}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${BOLD_MAGENTA}💖 感謝使用，歡迎關注作者！${NC}                          ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${RED}🎬 B 站${NC}: space.bilibili.com/1765875510                      ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${CYAN}📱 抖音/YouTube/TikTok${NC}: 是程星哒                        ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${GREEN}💬 QQ 粉絲群${NC}: 810288129                                   ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${BOLD_YELLOW}⭐ 如果腳本對你有幫助，請給個三連支持！${NC}              ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${BOLD_YELLOW}   點贊 + 投幣 + 收藏 = 作者更新動力${NC}                    ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${MAGENTA}🤖 千問 AI${NC}: https://tongyi.aliyun.com/qianwen          ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}        ${GREEN}🔄 轉轉${NC}: https://www.zhuanzhuan.com                     ${WHITE}║${NC}"
    echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
    echo -e "${WHITE}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

# ==================== 多語言文本 - 簡體中文 ====================
L_zh_CN_title="自动设置 DNS 脚本 (增强交互版)"
L_zh_CN_copyright="版权所有 (C) 2020-2026 程星博客"
L_zh_CN_sponsors="赞助商：千问 AI | 转转二手"
L_zh_CN_version="版本号"
L_zh_CN_select_lang="选择语言 / Select Language / 選擇語言"
L_zh_CN_zh_cn="简体中文"
L_zh_CN_zh_tw="繁體中文"
L_zh_CN_en="English"
L_zh_CN_select_ip_mode="选择 IP 协议模式"
L_zh_CN_ipv4_only="仅 IPv4"
L_zh_CN_ipv6_only="仅 IPv6"
L_zh_CN_dual_stack="IPv4 + IPv6 双栈"
L_zh_CN_ip_mode_selected="已选择 IP 模式"
L_zh_CN_testing="正在测试 DNS 响应速度 (500ms 超时)"
L_zh_CN_testing_v4="正在测试 IPv4 DNS"
L_zh_CN_testing_v6="正在测试 IPv6 DNS"
L_zh_CN_test_domain="测试域名"
L_zh_CN_complete="测试完成"
L_zh_CN_fastest="速度最快的 DNS"
L_zh_CN_step1="步骤 1: 选择首选 DNS 服务器"
L_zh_CN_primary="首选 DNS"
L_zh_CN_secondary="备用 DNS"
L_zh_CN_final="最终配置 DNS"
L_zh_CN_confirm_config="确认开始配置？(y/n)"
L_zh_CN_configuring="正在应用配置"
L_zh_CN_success="DNS 配置全部完成"
L_zh_CN_cancelled="操作已取消"
L_zh_CN_select_dns_type="选择 DNS 类型"
L_zh_CN_standard_dns="标准 DNS"
L_zh_CN_doh_dns="DoH 加密 DNS"
L_zh_CN_set_secondary="是否设置备用 DNS？(y/n，默认 n)"
L_zh_CN_skip_secondary="跳过备用 DNS 设置"
L_zh_CN_selected="已选择"
L_zh_CN_page="页"
L_zh_CN_timeout="超时"
L_zh_CN_recommended="★推荐"
L_zh_CN_custom="自定义 DNS"
L_zh_CN_enter_primary="请输入首选 DNS IP"
L_zh_CN_enter_secondary="请输入备用 DNS IP"
L_zh_CN_invalid_input="输入无效，请重新输入"
L_zh_CN_need_root="此脚本需要 root 权限运行，请使用 sudo 或切换到 root 用户"
L_zh_CN_detect_os="检测到操作系统"
L_zh_CN_detect_net="检测到网络管理方式"
L_zh_CN_detect_iface="检测到活动网络接口"
L_zh_CN_verify="验证 DNS 配置"
L_zh_CN_verify_success="DNS 解析测试成功"
L_zh_CN_verify_failed="DNS 解析测试失败"
L_zh_CN_sponsor="感谢以下赞助商支持"
L_zh_CN_thanks="感谢使用本脚本，更多资源请访问 程星博客"
L_zh_CN_pipe_error="检测到脚本通过管道执行，交互式功能将无法使用"
L_zh_CN_pipe_fix="请改用以下方式执行"
L_zh_CN_navigate="↑/↓ 选择  |  ←/→ 翻页  |  Enter 确认  |  0 自定义  |  q 返回"
L_zh_CN_testing_dns="正在测试"
L_zh_CN_press_skip="按 T 跳过测试"
L_zh_CN_test_skipped="已跳过测试，使用默认值"
L_zh_CN_server_info="服务器信息"
L_zh_CN_ip_address="IP 地址"
L_zh_CN_v6_address="IPv6 地址"
L_zh_CN_location="地理位置"
L_zh_CN_isp="运营商"
L_zh_CN_network="网络支持"
L_zh_CN_ipv4_supported="IPv4 支持"
L_zh_CN_ipv6_supported="IPv6 支持"
L_zh_CN_yes="是"
L_zh_CN_no="否"
L_zh_CN_detecting="正在检测"
L_zh_CN_tailscale_warn="⚠️  检测到 Tailscale，DNS 可能被覆盖"
L_zh_CN_tailscale_fix="请手动配置或临时禁用 Tailscale"
L_zh_CN_backup_created="配置已备份到"
L_zh_CN_backup_dir="备份目录"
L_zh_CN_restoring="正在恢复备份配置"
L_zh_CN_restore_success="备份配置恢复成功"
L_zh_CN_no_backup="未找到备份文件"
L_zh_CN_loading="加载中"
L_zh_CN_processing="处理中"
L_zh_CN_please_wait="请稍候"
L_zh_CN_error_occurred="发生错误"
L_zh_CN_retry="重试"
L_zh_CN_exit="退出"
L_zh_CN_main_menu="主菜单"
L_zh_CN_test_dns="测试 DNS 速度"
L_zh_CN_view_config="查看当前配置"
L_zh_CN_restore_backup="恢复备份配置"
L_zh_CN_exit_script="退出脚本"

# ==================== 多語言文本 - 繁體中文 ====================
L_zh_TW_title="自動設置 DNS 腳本 (增強交互版)"
L_zh_TW_copyright="版權所有 (C) 2020-2026 程星博客"
L_zh_TW_sponsors="贊助商：千問 AI | 轉轉二手"
L_zh_TW_version="版本號"
L_zh_TW_select_lang="選擇語言 / Select Language / 选择语言"
L_zh_TW_zh_cn="简体中文"
L_zh_TW_zh_tw="繁體中文"
L_zh_TW_en="English"
L_zh_TW_select_ip_mode="選擇 IP 協議模式"
L_zh_TW_ipv4_only="僅 IPv4"
L_zh_TW_ipv6_only="僅 IPv6"
L_zh_TW_dual_stack="IPv4 + IPv6 雙棧"
L_zh_TW_ip_mode_selected="已選擇 IP 模式"
L_zh_TW_testing="正在測試 DNS 響應速度 (500ms 超時)"
L_zh_TW_testing_v4="正在測試 IPv4 DNS"
L_zh_TW_testing_v6="正在測試 IPv6 DNS"
L_zh_TW_test_domain="測試域名"
L_zh_TW_complete="測試完成"
L_zh_TW_fastest="速度最快的 DNS"
L_zh_TW_step1="步驟 1: 選擇首選 DNS 服務器"
L_zh_TW_primary="首選 DNS"
L_zh_TW_secondary="備用 DNS"
L_zh_TW_final="最終配置 DNS"
L_zh_TW_confirm_config="確認開始配置？(y/n)"
L_zh_TW_configuring="正在應用配置"
L_zh_TW_success="DNS 配置全部完成"
L_zh_TW_cancelled="操作已取消"
L_zh_TW_select_dns_type="選擇 DNS 類型"
L_zh_TW_standard_dns="標準 DNS"
L_zh_TW_doh_dns="DoH 加密 DNS"
L_zh_TW_set_secondary="是否設置備用 DNS？(y/n，默認 n)"
L_zh_TW_skip_secondary="跳過備用 DNS 設置"
L_zh_TW_selected="已選擇"
L_zh_TW_page="頁"
L_zh_TW_timeout="超時"
L_zh_TW_recommended="★推薦"
L_zh_TW_custom="自定義 DNS"
L_zh_TW_enter_primary="請輸入首選 DNS IP"
L_zh_TW_enter_secondary="請輸入備用 DNS IP"
L_zh_TW_invalid_input="輸入無效，請重新輸入"
L_zh_TW_need_root="此腳本需要 root 權限運行，請使用 sudo 或切換到 root 用戶"
L_zh_TW_detect_os="檢測到操作系統"
L_zh_TW_detect_net="檢測到網絡管理方式"
L_zh_TW_detect_iface="檢測到活動網絡接口"
L_zh_TW_verify="驗證 DNS 配置"
L_zh_TW_verify_success="DNS 解析測試成功"
L_zh_TW_verify_failed="DNS 解析測試失敗"
L_zh_TW_sponsor="感謝以下贊助商支持"
L_zh_TW_thanks="感謝使用本腳本，更多資源請訪問 程星博客"
L_zh_TW_pipe_error="檢測到腳本通過管道執行，交互式功能將無法使用"
L_zh_TW_pipe_fix="請改用以下方式執行"
L_zh_TW_navigate="↑/↓ 選擇  |  ←/→ 翻頁  |  Enter 確認  |  0 自定義  |  q 返回"
L_zh_TW_testing_dns="正在測試"
L_zh_TW_press_skip="按 T 跳過測試"
L_zh_TW_test_skipped="已跳過測試，使用默認值"
L_zh_TW_server_info="服務器信息"
L_zh_TW_ip_address="IP 地址"
L_zh_TW_v6_address="IPv6 地址"
L_zh_TW_location="地理位置"
L_zh_TW_isp="運營商"
L_zh_TW_network="網絡支持"
L_zh_TW_ipv4_supported="IPv4 支持"
L_zh_TW_ipv6_supported="IPv6 支持"
L_zh_TW_yes="是"
L_zh_TW_no="否"
L_zh_TW_detecting="正在檢測"
L_zh_TW_tailscale_warn="⚠️  檢測到 Tailscale，DNS 可能被覆蓋"
L_zh_TW_tailscale_fix="請手動配置或臨時禁用 Tailscale"
L_zh_TW_backup_created="配置已備份到"
L_zh_TW_backup_dir="備份目錄"
L_zh_TW_restoring="正在恢復備份配置"
L_zh_TW_restore_success="備份配置恢復成功"
L_zh_TW_no_backup="未找到備份文件"
L_zh_TW_loading="加載中"
L_zh_TW_processing="處理中"
L_zh_TW_please_wait="請稍候"
L_zh_TW_error_occurred="發生錯誤"
L_zh_TW_retry="重試"
L_zh_TW_exit="退出"
L_zh_TW_main_menu="主菜單"
L_zh_TW_test_dns="測試 DNS 速度"
L_zh_TW_view_config="查看當前配置"
L_zh_TW_restore_backup="恢復備份配置"
L_zh_TW_exit_script="退出腳本"

# ==================== 多語言文本 - English ====================
L_en_title="Auto DNS Setup Script (Enhanced)"
L_en_copyright="Copyright (C) 2020-2026 Chengxing Blog"
L_en_sponsors="Sponsors: Qianwen AI | Zhuanzhuan"
L_en_version="Version"
L_en_select_lang="Select Language / 选择语言 / 選擇語言"
L_en_zh_cn="简体中文"
L_en_zh_tw="繁體中文"
L_en_en="English"
L_en_select_ip_mode="Select IP Protocol Mode"
L_en_ipv4_only="IPv4 Only"
L_en_ipv6_only="IPv6 Only"
L_en_dual_stack="IPv4 + IPv6 Dual Stack"
L_en_ip_mode_selected="IP Mode Selected"
L_en_testing="Testing DNS Response Speed (500ms timeout)"
L_en_testing_v4="Testing IPv4 DNS"
L_en_testing_v6="Testing IPv6 DNS"
L_en_test_domain="Test Domain"
L_en_complete="Test Complete"
L_en_fastest="Fastest DNS"
L_en_step1="Step 1: Select Primary DNS Server"
L_en_primary="Primary DNS"
L_en_secondary="Secondary DNS"
L_en_final="Final DNS Configuration"
L_en_confirm_config="Confirm to start configuration? (y/n)"
L_en_configuring="Applying configuration"
L_en_success="DNS configuration completed"
L_en_cancelled="Operation cancelled"
L_en_select_dns_type="Select DNS Type"
L_en_standard_dns="Standard DNS"
L_en_doh_dns="DoH Encrypted DNS"
L_en_set_secondary="Set secondary DNS? (y/n, default n)"
L_en_skip_secondary="Skip secondary DNS"
L_en_selected="Selected"
L_en_page="Page"
L_en_timeout="Timeout"
L_en_recommended="★Recommended"
L_en_custom="Custom DNS"
L_en_enter_primary="Enter primary DNS IP"
L_en_enter_secondary="Enter secondary DNS IP"
L_en_invalid_input="Invalid input, please try again"
L_en_need_root="This script requires root privileges, please use sudo or switch to root"
L_en_detect_os="Detected OS"
L_en_detect_net="Detected Network Manager"
L_en_detect_iface="Detected Active Interface"
L_en_verify="Verifying DNS Configuration"
L_en_verify_success="DNS resolution test successful"
L_en_verify_failed="DNS resolution test failed"
L_en_sponsor="Thanks to our sponsors"
L_en_thanks="Thank you for using this script. Visit Chengxing Blog for more resources"
L_en_pipe_error="Script detected running via pipe, interactive features unavailable"
L_en_pipe_fix="Please use the following method instead"
L_en_navigate="↑/↓ Select  |  ←/→ Page  |  Enter Confirm  |  0 Custom  |  q Back"
L_en_testing_dns="Testing"
L_en_press_skip="Press T to skip"
L_en_test_skipped="Test skipped, using defaults"
L_en_server_info="Server Information"
L_en_ip_address="IP Address"
L_en_v6_address="IPv6 Address"
L_en_location="Location"
L_en_isp="ISP"
L_en_network="Network Support"
L_en_ipv4_supported="IPv4 Support"
L_en_ipv6_supported="IPv6 Support"
L_en_yes="Yes"
L_en_no="No"
L_en_detecting="Detecting"
L_en_tailscale_warn="⚠️  Tailscale detected, DNS may be overwritten"
L_en_tailscale_fix="Please configure manually or disable Tailscale"
L_en_backup_created="Configuration backed up to"
L_en_backup_dir="Backup Directory"
L_en_restoring="Restoring backup configuration"
L_en_restore_success="Backup configuration restored successfully"
L_en_no_backup="No backup file found"
L_en_loading="Loading"
L_en_processing="Processing"
L_en_please_wait="Please wait"
L_en_error_occurred="Error occurred"
L_en_retry="Retry"
L_en_exit="Exit"
L_en_main_menu="Main Menu"
L_en_test_dns="Test DNS Speed"
L_en_view_config="View Current Configuration"
L_en_restore_backup="Restore Backup Configuration"
L_en_exit_script="Exit Script"

# ==================== 語言文本獲取函數 ====================
get_text() {
    local key="$1"
    local var_name="L_${CURRENT_LANG}_${key}"
    echo "${!var_name:-$key}"
}

# ==================== 日誌函數 ====================
log_info()    { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warn()    { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error()   { echo -e "${RED}[ERROR]${NC} $1"; }
log_debug()   { [[ "${DEBUG:-0}" == "1" ]] && echo -e "${GRAY}[DEBUG]${NC} $1" || true; }
log_header()  { echo -e "${CYAN}════════════════════════════════════════════════════${NC}"; }
log_subheader() { echo -e "${DIM}────────────────────────────────────────────────────${NC}"; }

# ==================== 進度條函數 ====================
show_progress() {
    local current=$1
    local total=$2
    local message=$3
    local bar_width=40
    local percent=$((current * 100 / total))
    local filled=$((current * bar_width / total))
    local empty=$((bar_width - filled))
    
    printf "\r${CYAN}[%${filled}s${NC}${DIM}%${empty}s${NC}] ${percent}%% - ${message}" "$(printf '#%.0s' $(seq 1 $filled))" "$(printf ' %.0s' $(seq 1 $empty))"
}

# ==================== 終端清理 ====================
cleanup() {
    # 恢復終端設置
    stty echo icanon 2>/dev/null || true
    
    # 清理背景進程
    if [[ -n "$LISTEN_PID" ]] && kill -0 "$LISTEN_PID" 2>/dev/null; then
        kill "$LISTEN_PID" 2>/dev/null || true
        wait "$LISTEN_PID" 2>/dev/null || true
    fi
    
    # 恢復顏色
    echo -e "${NC}"
    
    # 顯示光標
    tput cnorm 2>/dev/null || true
}
trap cleanup EXIT INT TERM HUP

# ==================== 隱藏/顯示光標 ====================
hide_cursor() { tput civis 2>/dev/null || true; }
show_cursor() { tput cnorm 2>/dev/null || true; }

# ==================== Tailscale 檢測 ====================
check_tailscale() {
    log_debug "Checking Tailscale status..."
    
    # 檢查 tailscale 命令
    if command -v tailscale &> /dev/null; then
        if tailscale status &> /dev/null; then
            TAILSCALE_ACTIVE=1
            log_debug "Tailscale is active (command check)"
            return 0
        fi
    fi
    
    # 檢查 /etc/resolv.conf
    if grep -q "tailscale" /etc/resolv.conf 2>/dev/null; then
        TAILSCALE_ACTIVE=1
        log_debug "Tailscale is active (resolv.conf check)"
        return 0
    fi
    
    # 檢查 systemd-resolved 配置
    if [[ -f /etc/systemd/resolved.conf.d/tailscale.conf ]]; then
        TAILSCALE_ACTIVE=1
        log_debug "Tailscale is active (systemd config check)"
        return 0
    fi
    
    # 檢查 NetworkManager 配置
    if grep -r "tailscale" /etc/NetworkManager/ 2>/dev/null | grep -q "dns"; then
        TAILSCALE_ACTIVE=1
        log_debug "Tailscale is active (NetworkManager check)"
        return 0
    fi
    
    TAILSCALE_ACTIVE=0
    log_debug "Tailscale is not active"
    return 1
}

handle_tailscale() {
    if [[ $TAILSCALE_ACTIVE -eq 1 ]]; then
        echo ""
        log_warn "$(get_text tailscale_warn)"
        echo ""
        echo -e "${WHITE}╔══════════════════════════════════════════════════════════════╗${NC}"
        echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}  ${BOLD_YELLOW}⚠️  Tailscale 會覆蓋系統 DNS 配置${NC}                              ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}  ${BOLD_GREEN}解決方案：${NC}                                                     ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}  1. 臨時禁用 Tailscale DNS:                                   ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}     ${CYAN}sudo tailscale set --accept-dns=false${NC}                    ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}  2. 永久配置 Tailscale DNS:                                   ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}     ${CYAN}sudo tailscale set --dns=223.5.5.5,223.6.6.6${NC}             ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}  3. 繼續配置（重啟後可能被覆蓋）:                             ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}     按 Enter 繼續                                            ${WHITE}║${NC}"
        echo -e "${WHITE}║${NC}                                                              ${WHITE}║${NC}"
        echo -e "${WHITE}╚══════════════════════════════════════════════════════════════╝${NC}"
        echo ""
        
        printf "${YELLOW}請選擇 (1/2/3 或 Enter 繼續): ${NC}"
        read ts_choice
        
        case "$ts_choice" in
            1)
                if command -v tailscale &> /dev/null; then
                    log_info "正在禁用 Tailscale DNS..."
                    if tailscale set --accept-dns=false 2>/dev/null; then
                        log_success "已禁用 Tailscale DNS"
                    else
                        log_warn "禁用 Tailscale DNS 失敗"
                    fi
                else
                    log_warn "tailscale 命令不可用"
                fi
                ;;
            2)
                if command -v tailscale &> /dev/null; then
                    printf "${YELLOW}請輸入要設置的 DNS (用逗號分隔，例如 223.5.5.5,223.6.6.6): ${NC}"
                    read ts_dns
                    if [[ -n "$ts_dns" ]]; then
                        log_info "正在配置 Tailscale DNS..."
                        if tailscale set --dns="$ts_dns" 2>/dev/null; then
                            log_success "已配置 Tailscale DNS: $ts_dns"
                            return 0
                        else
                            log_warn "配置 Tailscale DNS 失敗"
                        fi
                    fi
                else
                    log_warn "tailscale 命令不可用"
                fi
                ;;
            3|"")
                log_info "繼續配置（注意：重啟後可能被 Tailscale 覆蓋）"
                ;;
            *)
                log_warn "無效選擇，繼續配置"
                ;;
        esac
    fi
}

# ==================== IPv4 連通性檢測 ====================
check_ipv4() {
    log_debug "Checking IPv4 connectivity..."
    
    # 嘗試 ping 多個公共 DNS
    local test_hosts=("8.8.8.8" "1.1.1.1" "223.5.5.5")
    
    for host in "${test_hosts[@]}"; do
        if ping -c 1 -W 2 "$host" &>/dev/null; then
            IPV4_SUPPORTED=1
            log_debug "IPv4 is supported (tested with $host)"
            return 0
        fi
    done
    
    IPV4_SUPPORTED=0
    log_debug "IPv4 is not supported"
    return 1
}

# ==================== IPv6 連通性檢測 ====================
check_ipv6() {
    log_debug "Checking IPv6 connectivity..."
    
    # 嘗試 ping6 多個公共 DNS
    local test_hosts=("2001:4860:4860::8888" "2606:4700:4700::1111" "2400:3200::1")
    
    for host in "${test_hosts[@]}"; do
        # 嘗試 ping6
        if command -v ping6 &> /dev/null; then
            if ping6 -c 1 -W 2 "$host" &>/dev/null; then
                IPV6_SUPPORTED=1
                log_debug "IPv6 is supported (tested with $host using ping6)"
                return 0
            fi
        fi
        
        # 嘗試 ping -6
        if ping -6 -c 1 -W 2 "$host" &>/dev/null; then
            IPV6_SUPPORTED=1
            log_debug "IPv6 is supported (tested with $host using ping -6)"
            return 0
        fi
    done
    
    IPV6_SUPPORTED=0
    log_debug "IPv6 is not supported"
    return 1
}

# ==================== 獲取服務器信息 ====================
get_server_info() {
    log_info "$(get_text detecting) $(get_text server_info)..."
    echo ""
    
    # 先檢測網絡連通性
    check_ipv4
    check_ipv6
    
    # 獲取 IP 信息（優先 IPv4）
    if [[ $IPV4_SUPPORTED -eq 1 ]]; then
        local api_urls=(
            "https://ipapi.co/json/"
            "https://ipwho.is/"
            "https://ip-api.com/json/"
            "https://api.ip.sb/geoip"
        )
        
        for api_url in "${api_urls[@]}"; do
            log_debug "Trying API: $api_url"
            local response
            response=$(curl -s -m 5 --connect-timeout 3 "$api_url" 2>/dev/null) || continue
            
            if [[ -n "$response" ]]; then
                if [[ "$api_url" == *"ipapi.co"* ]]; then
                    SERVER_IP=$(echo "$response" | grep -o '"ip":"[^"]*"' | cut -d'"' -f4)
                    SERVER_LOCATION=$(echo "$response" | grep -o '"city":"[^"]*"' | cut -d'"' -f4)
                    local region=$(echo "$response" | grep -o '"region":"[^"]*"' | cut -d'"' -f4)
                    local country=$(echo "$response" | grep -o '"country_name":"[^"]*"' | cut -d'"' -f4)
                    SERVER_ISP=$(echo "$response" | grep -o '"org":"[^"]*"' | cut -d'"' -f4)
                    [[ -n "$region" ]] && SERVER_LOCATION="${SERVER_LOCATION}, ${region}"
                    [[ -n "$country" ]] && SERVER_LOCATION="${SERVER_LOCATION}, ${country}"
                elif [[ "$api_url" == *"ipwho.is"* ]]; then
                    SERVER_IP=$(echo "$response" | grep -o '"ip":"[^"]*"' | cut -d'"' -f4)
                    SERVER_LOCATION=$(echo "$response" | grep -o '"city":"[^"]*"' | cut -d'"' -f4)
                    local region=$(echo "$response" | grep -o '"region":"[^"]*"' | cut -d'"' -f4)
                    local country=$(echo "$response" | grep -o '"country":"[^"]*"' | cut -d'"' -f4)
                    SERVER_ISP=$(echo "$response" | grep -o '"connection":{"isp":"[^"]*"' | cut -d'"' -f4)
                    [[ -n "$region" ]] && SERVER_LOCATION="${SERVER_LOCATION}, ${region}"
                    [[ -n "$country" ]] && SERVER_LOCATION="${SERVER_LOCATION}, ${country}"
                elif [[ "$api_url" == *"ip-api.com"* ]]; then
                    SERVER_IP=$(echo "$response" | grep -o '"query":"[^"]*"' | cut -d'"' -f4)
                    SERVER_LOCATION=$(echo "$response" | grep -o '"city":"[^"]*"' | cut -d'"' -f4)
                    local region=$(echo "$response" | grep -o '"regionName":"[^"]*"' | cut -d'"' -f4)
                    local country=$(echo "$response" | grep -o '"country":"[^"]*"' | cut -d'"' -f4)
                    SERVER_ISP=$(echo "$response" | grep -o '"isp":"[^"]*"' | cut -d'"' -f4)
                    [[ -n "$region" ]] && SERVER_LOCATION="${SERVER_LOCATION}, ${region}"
                    [[ -n "$country" ]] && SERVER_LOCATION="${SERVER_LOCATION}, ${country}"
                elif [[ "$api_url" == *"ip.sb"* ]]; then
                    SERVER_IP=$(echo "$response" | grep -o '"ip":"[^"]*"' | cut -d'"' -f4)
                    SERVER_LOCATION=$(echo "$response" | grep -o '"city":"[^"]*"' | cut -d'"' -f4)
                    local country=$(echo "$response" | grep -o '"country":"[^"]*"' | cut -d'"' -f4)
                    SERVER_ISP=$(echo "$response" | grep -o '"isp":"[^"]*"' | cut -d'"' -f4)
                    [[ -n "$country" ]] && SERVER_LOCATION="${SERVER_LOCATION}, ${country}"
                fi
                
                if [[ -n "$SERVER_IP" ]]; then
                    log_debug "Successfully got server info from $api_url"
                    break
                fi
            fi
        done
    fi
    
    # 獲取 IPv6 地址
    if [[ $IPV6_SUPPORTED -eq 1 ]]; then
        local ipv6_addr=$(ip -6 addr show scope global 2>/dev/null | grep -oP 'inet6 \K[0-9a-f:]+' | grep -v '^fe80:' | head -1)
        if [[ -z "$ipv6_addr" ]]; then
            ipv6_addr=$(curl -s -m 5 https://api64.ipify.org 2>/dev/null)
        fi
        if [[ -n "$ipv6_addr" ]]; then
            log_debug "IPv6 address: $ipv6_addr"
        fi
    fi
    
    show_server_info
}

# ==================== 顯示服務器信息 ====================
show_server_info() {
    echo ""
    echo -e "${WHITE}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${WHITE}║${NC}        ${BOLD_MAGENTA}🖥️ $(get_text server_info)${NC}                                  ${WHITE}║${NC}"
    echo -e "${WHITE}╠══════════════════════════════════════════════════════════════╣${NC}"
    
    if [[ -n "$SERVER_IP" ]]; then
        printf "${WHITE}║${NC}  ${GREEN}📍 $(get_text ip_address)${NC}: %-40s ${WHITE}║${NC}\n" "$SERVER_IP"
    else
        printf "${WHITE}║${NC}  ${YELLOW}📍 $(get_text ip_address)${NC}: %-40s ${WHITE}║${NC}\n" "$(get_text no)"
    fi
    
    if [[ -n "$SERVER_LOCATION" ]]; then
        printf "${WHITE}║${NC}  ${GREEN}🌍 $(get_text location)${NC}: %-40s ${WHITE}║${NC}\n" "$SERVER_LOCATION"
    else
        printf "${WHITE}║${NC}  ${YELLOW}🌍 $(get_text location)${NC}: %-40s ${WHITE}║${NC}\n" "$(get_text no)"
    fi
    
    if [[ -n "$SERVER_ISP" ]]; then
        printf "${WHITE}║${NC}  ${GREEN}📡 $(get_text isp)${NC}: %-40s ${WHITE}║${NC}\n" "$SERVER_ISP"
    else
        printf "${WHITE}║${NC}  ${YELLOW}📡 $(get_text isp)${NC}: %-40s ${WHITE}║${NC}\n" "$(get_text no)"
    fi
    
    echo -e "${WHITE}╠══════════════════════════════════════════════════════════════╣${NC}"
    
    if [[ $IPV4_SUPPORTED -eq 1 ]]; then
        printf "${WHITE}║${NC}  ${GREEN}✅ $(get_text ipv4_supported)${NC}: %-38s ${WHITE}║${NC}\n" "$(get_text yes)"
    else
        printf "${WHITE}║${NC}  ${RED}❌ $(get_text ipv4_supported)${NC}: %-38s ${WHITE}║${NC}\n" "$(get_text no)"
    fi
    
    if [[ $IPV6_SUPPORTED -eq 1 ]]; then
        printf "${WHITE}║${NC}  ${GREEN}✅ $(get_text ipv6_supported)${NC}: %-38s ${WHITE}║${NC}\n" "$(get_text yes)"
    else
        printf "${WHITE}║${NC}  ${RED}❌ $(get_text ipv6_supported)${NC}: %-38s ${WHITE}║${NC}\n" "$(get_text no)"
    fi
    
    echo -e "${WHITE}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

# ==================== 語言選擇 ====================
select_language() {
    local lang_options=("zh_CN" "zh_TW" "en")
    local current=0
    
    while true; do
        clear
        echo ""
        log_header
        echo -e "   ${BOLD_WHITE}$(get_text select_lang)${NC}"
        log_header
        echo ""
        
        local names=()
        names+=("$(get_text zh_cn)")
        names+=("$(get_text zh_tw)")
        names+=("$(get_text en)")
        
        for i in 0 1 2; do
            if [[ $i -eq $current ]]; then
                echo -e "  ${GREEN}▶ ${BOLD_WHITE}${names[$i]}${NC}"
            else
                echo "    ${DIM}${names[$i]}${NC}"
            fi
        done
        
        echo ""
        echo -e "  ${DIM}$(get_text navigate)${NC}"
        echo ""
        
        local key=""
        read -rsn1 key 2>/dev/null || key=""
        
        if [[ "$key" == $'\x1b' ]]; then
            read -rsn2 key2 2>/dev/null || key2=""
            key="$key$key2"
        fi
        
        case "$key" in
            $'\x1b[A') current=$((current - 1)); [[ $current -lt 0 ]] && current=2 ;;
            $'\x1b[B') current=$((current + 1)); [[ $current -gt 2 ]] && current=0 ;;
            '') CURRENT_LANG="${lang_options[$current]}"; echo ""; log_success "Language: ${lang_options[$current]}"; sleep 0.3; return 0 ;;
            'q'|'Q') exit 0 ;;
        esac
    done
}

# ==================== IP 模式選擇 ====================
select_ip_mode() {
    local current=0
    
    while true; do
        clear
        echo ""
        log_header
        echo -e "   ${BOLD_WHITE}$(get_text select_ip_mode)${NC}"
        log_header
        echo ""
        
        # 根據實際網絡支持情況調整選項
        local available_modes=()
        local available_names=()
        
        if [[ $IPV4_SUPPORTED -eq 1 ]]; then
            available_modes+=("ipv4")
            available_names+=("$(get_text ipv4_only)")
        fi
        
        if [[ $IPV6_SUPPORTED -eq 1 ]]; then
            available_modes+=("ipv6")
            available_names+=("$(get_text ipv6_only)")
        fi
        
        if [[ $IPV4_SUPPORTED -eq 1 && $IPV6_SUPPORTED -eq 1 ]]; then
            available_modes+=("dual")
            available_names+=("$(get_text dual_stack)")
        fi
        
        if [[ ${#available_modes[@]} -eq 0 ]]; then
            log_error "未檢測到可用的網絡連接"
            sleep 2
            exit 1
        fi
        
        # 如果只有一種模式可用，直接選擇
        if [[ ${#available_modes[@]} -eq 1 ]]; then
            IP_MODE="${available_modes[0]}"
            log_success "$(get_text ip_mode_selected): ${available_names[0]}"
            sleep 0.5
            return 0
        fi
        
        for i in "${!available_names[@]}"; do
            if [[ $i -eq $current ]]; then
                echo -e "  ${GREEN}▶ ${BOLD_WHITE}${available_names[$i]}${NC}"
            else
                echo "    ${DIM}${available_names[$i]}${NC}"
            fi
        done
        
        echo ""
        echo -e "  ${DIM}$(get_text navigate)${NC}"
        echo ""
        
        local key=""
        read -rsn1 key 2>/dev/null || key=""
        
        if [[ "$key" == $'\x1b' ]]; then
            read -rsn2 key2 2>/dev/null || key2=""
            key="$key$key2"
        fi
        
        case "$key" in
            $'\x1b[A') current=$((current - 1)); [[ $current -lt 0 ]] && current=$((${#available_modes[@]} - 1)) ;;
            $'\x1b[B') current=$((current + 1)); [[ $current -gt $((${#available_modes[@]} - 1)) ]] && current=0 ;;
            '') IP_MODE="${available_modes[$current]}"; echo ""; log_success "$(get_text ip_mode_selected): ${available_names[$current]}"; sleep 0.3; return 0 ;;
            'q'|'Q') exit 0 ;;
        esac
    done
}

# ==================== 管道檢測 ====================
check_pipe() {
    if [[ ! -t 0 ]]; then
        log_error "$(get_text pipe_error)"
        echo ""
        echo "$(get_text pipe_fix):"
        echo "  ${CYAN}curl -o dnsxg.sh https://xz.xn--kiv765b.top/dnsxg.sh${NC}"
        echo "  ${CYAN}chmod +x dnsxg.sh && sudo ./dnsxg.sh${NC}"
        echo ""
        exit 1
    fi
}

# ==================== 版權信息 ====================
show_copyright() {
    echo ""
    log_header
    echo -e "   ${BOLD_WHITE}$(get_text title)${NC}"
    echo -e "   ${DIM}$(get_text copyright)${NC}"
    echo -e "   ${DIM}$(get_text sponsors)${NC}"
    echo -e "   ${DIM}$(get_text version): ${SCRIPT_VERSION}${NC}"
    log_header
}

# ==================== Root 權限檢查 ====================
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "$(get_text need_root)"
        echo ""
        echo -e "${YELLOW}提示：${NC}請使用以下命令運行腳本"
        echo -e "  ${CYAN}sudo $0${NC}"
        echo ""
        exit 1
    fi
}

# ==================== 操作系統檢測 ====================
detect_os() {
    if [[ -f /etc/os-release ]]; then
        . /etc/os-release
        log_info "$(get_text detect_os): ${BOLD_WHITE}$PRETTY_NAME${NC}"
    elif [[ -f /etc/centos-release ]]; then
        log_info "$(get_text detect_os): ${BOLD_WHITE}CentOS${NC}"
    elif [[ -f /etc/redhat-release ]]; then
        log_info "$(get_text detect_os): ${BOLD_WHITE}Red Hat Enterprise Linux${NC}"
    elif [[ -f /etc/arch-release ]]; then
        log_info "$(get_text detect_os): ${BOLD_WHITE}Arch Linux${NC}"
    elif [[ -f /etc/debian_version ]]; then
        log_info "$(get_text detect_os): ${BOLD_WHITE}Debian$(cat /etc/debian_version)${NC}"
    else
        log_warn "無法識別操作系統，將使用通用配置方式"
    fi
}

# ==================== 網絡管理器檢測 ====================
detect_network_manager() {
    if command -v netplan &> /dev/null && [[ -d /etc/netplan ]]; then
        NETWORK_MANAGER="netplan"
    elif command -v nmcli &> /dev/null; then
        NETWORK_MANAGER="networkmanager"
    elif command -v systemd-networkd &> /dev/null; then
        NETWORK_MANAGER="systemd-networkd"
    elif [[ -d /etc/sysconfig/network-scripts ]]; then
        NETWORK_MANAGER="network-scripts"
    elif [[ -f /etc/network/interfaces ]]; then
        NETWORK_MANAGER="interfaces"
    else
        NETWORK_MANAGER="generic"
    fi
    log_info "$(get_text detect_net): ${BOLD_WHITE}$NETWORK_MANAGER${NC}"
}

# ==================== 獲取活動網絡接口 ====================
get_active_interface() {
    # 嘗試多種方法獲取活動接口
    INTERFACE=$(ip route 2>/dev/null | grep default | awk '{print $5}' | head -1)
    
    if [[ -z "$INTERFACE" ]]; then
        INTERFACE=$(ip -o link show 2>/dev/null | awk -F': ' '$2 ~ /UP/ && $1 !~ /lo/ {print $2}' | head -1)
    fi
    
    if [[ -z "$INTERFACE" ]]; then
        # 嘗試讀取 /sys 目錄
        for iface in /sys/class/net/*; do
            if [[ -f "$iface/operstate" ]] && [[ "$(cat "$iface/operstate" 2>/dev/null)" == "up" ]]; then
                INTERFACE=$(basename "$iface")
                [[ "$INTERFACE" != "lo" ]] && break
            fi
        done
    fi
    
    if [[ -z "$INTERFACE" ]]; then
        INTERFACE="eth0"
        log_warn "無法檢測活動接口，使用默認值：$INTERFACE"
    else
        log_info "$(get_text detect_iface): ${BOLD_WHITE}$INTERFACE${NC}"
    fi
}

# ==================== 創建備份目錄 ====================
create_backup_dir() {
    BACKUP_DIR="/root/dns_backup/$(date +%Y%m%d_%H%M%S)"
    
    if mkdir -p "$BACKUP_DIR" 2>/dev/null; then
        BACKUP_CREATED=1
        log_debug "Backup directory created: $BACKUP_DIR"
    else
        log_warn "無法創建備份目錄"
    fi
}

# ==================== 備份當前配置 ====================
backup_current_config() {
    if [[ $BACKUP_CREATED -eq 0 ]]; then
        create_backup_dir
    fi
    
    if [[ $BACKUP_CREATED -eq 1 ]]; then
        # 備份 resolv.conf
        if [[ -f /etc/resolv.conf ]]; then
            cp /etc/resolv.conf "$BACKUP_DIR/resolv.conf.bak" 2>/dev/null
            log_debug "Backed up /etc/resolv.conf"
        fi
        
        # 備份 systemd-resolved 配置
        if [[ -f /etc/systemd/resolved.conf ]]; then
            cp /etc/systemd/resolved.conf "$BACKUP_DIR/resolved.conf.bak" 2>/dev/null
            log_debug "Backed up /etc/systemd/resolved.conf"
        fi
        
        # 備份 netplan 配置
        if [[ -d /etc/netplan ]]; then
            cp -r /etc/netplan "$BACKUP_DIR/netplan.bak" 2>/dev/null
            log_debug "Backed up /etc/netplan"
        fi
        
        # 保存配置信息
        cat > "$BACKUP_DIR/config_info.txt" << EOF
備份時間：$(date)
IP 模式：$IP_MODE
網絡管理器：$NETWORK_MANAGER
活動接口：$INTERFACE
EOF
        
        log_info "$(get_text backup_created): ${CYAN}$BACKUP_DIR${NC}"
    fi
}

# ==================== DNS 數據庫 (IPv4) ====================
# 國內 DNS
declare -a DNS_NAME_CN=("阿里 DNS" "騰訊 DNS" "114DNS" "114DNS 安全版" "114DNS 家庭版" "百度 DNS" "360 DNS" "360 DNS 備用" "CNNIC DNS" "CNNIC 安全 DNS" "DNS 派" "OneDNS" "OneDNS 家庭版" "華為 DNS" "搜狐 DNS")
declare -a DNS_PRIMARY_CN=("223.5.5.5" "119.29.29.29" "114.114.114.114" "114.114.114.119" "114.114.114.110" "180.76.76.76" "101.226.4.6" "101.132.183.99" "1.2.4.8" "1.2.4.8" "101.132.183.98" "117.50.10.10" "117.50.10.11" "101.132.183.166" "123.123.123.123")
declare -a DNS_SECONDARY_CN=("223.6.6.6" "182.254.116.116" "114.114.115.115" "114.114.115.119" "114.114.115.110" "180.76.76.77" "218.30.118.6" "123.125.81.6" "210.2.4.8" "1.2.8.8" "101.132.184.188" "52.80.52.52" "52.80.52.53" "101.132.183.167" "123.132.123.124")
declare -a DNS_DESC_CN=("國內最快" "遊戲加速" "國內最早" "攔截釣魚" "過濾不良" "百度出品" "安全攔截" "雙線優化" "CNNIC" "支持 DNSSEC" "低延遲" "威脅情報" "家庭保護" "企業級" "搜狐推薦")
declare -a DNS_IPV6_CN=("2400:3200::1" "2402:4e00::" "2400:3200:baba::1" "2400:3200:baba::1" "2400:3200:baba::1" "2409:8c54::1" "2400:3200::1" "2400:3200::1" "2400:3200::1" "2400:3200::1" "2400:3200::1" "2400:3200::1" "2400:3200::1" "2400:3200::1" "2400:3200::1")
declare -a DNS_IPV6_SECONDARY_CN=("2400:3200:baba::1" "2402:4e00::1" "2400:3200::1" "2400:3200::1" "2400:3200::1" "2409:8c54::2" "2400:3200:baba::1" "2400:3200:baba::1" "2400:3200:baba::1" "2400:3200:baba::1" "2400:3200:baba::1" "2400:3200:baba::1" "2400:3200:baba::1" "2400:3200:baba::1" "2400:3200:baba::1")

# 國際 DNS
declare -a DNS_NAME_INT=("Google DNS" "Cloudflare DNS" "Cloudflare 安全" "Cloudflare 家庭" "Quad9 DNS" "OpenDNS" "OpenDNS Family" "Verisign DNS" "IBM Quad8" "CleanBrowsing" "AdGuard DNS" "AdGuard 家庭" "NextDNS" "Control D" "V2EX DNS")
declare -a DNS_PRIMARY_INT=("8.8.8.8" "1.1.1.1" "1.1.1.2" "1.1.1.3" "9.9.9.9" "208.67.222.222" "208.67.222.123" "64.6.64.6" "8.26.56.26" "185.228.168.9" "94.140.14.14" "94.140.14.15" "45.90.28.0" "76.76.2.0" "199.91.73.222")
declare -a DNS_SECONDARY_INT=("8.8.4.4" "1.0.0.1" "1.0.0.2" "1.0.0.3" "149.112.112.112" "208.67.220.220" "208.67.220.123" "64.6.65.6" "8.20.247.20" "185.228.169.9" "94.140.15.15" "94.140.15.16" "45.90.30.0" "76.76.10.0" "178.79.131.110")
declare -a DNS_DESC_INT=("全球知名" "全球最快" "攔截惡意" "過濾成人" "專注安全" "Cisco 旗下" "家庭過濾" "域名註冊商" "IBM 收購" "家庭安全" "去廣告" "去廣告 + 家庭" "可定制" "可配置" "社區運營")
declare -a DNS_IPV6_INT=("2001:4860:4860::8888" "2606:4700:4700::1111" "2606:4700:4700::1112" "2606:4700:4700::1113" "2620:fe::fe" "2620:119:35::35" "2620:119:53::53" "2610:a1:1018::1" "2610:a1:1019::1" "2a10:50c0::1:ff" "2a10:50c0::1:ff" "2a10:50c0::1:ff" "2a10:50c0::1:ff" "2a10:50c0::1:ff" "2a10:50c0::1:ff")
declare -a DNS_IPV6_SECONDARY_INT=("2001:4860:4860::8844" "2606:4700:4700::1001" "2606:4700:4700::1002" "2606:4700:4700::1003" "2620:fe::9" "2620:119:53::53" "2620:119:35::35" "2610:a1:1019::1" "2610:a1:1018::1" "2a10:50c0::2:ff" "2a10:50c0::2:ff" "2a10:50c0::2:ff" "2a10:50c0::2:ff" "2a10:50c0::2:ff" "2a10:50c0::2:ff")

# ISP DNS
declare -a DNS_NAME_ISP=("中國電信" "電信廣東" "電信北京" "電信上海" "中國聯通" "聯通北京" "聯通廣東" "中國移動" "移動北京" "移動廣東")
declare -a DNS_PRIMARY_ISP=("114.114.114.114" "202.96.128.86" "202.106.0.20" "202.96.209.5" "123.123.123.123" "202.106.0.20" "210.21.4.130" "211.136.192.6" "211.136.25.153" "211.136.17.107")
declare -a DNS_SECONDARY_ISP=("114.114.115.115" "202.96.128.166" "202.106.148.1" "202.96.209.133" "123.125.81.6" "202.106.196.115" "210.21.192.6" "211.136.112.50" "211.136.25.154" "211.136.17.108")
declare -a DNS_DESC_ISP=("電信首選" "廣東電信" "北京電信" "上海電信" "聯通推薦" "北京聯通" "廣東聯通" "移動推薦" "北京移動" "廣東移動")
declare -a DNS_IPV6_ISP=("240e:1:1::1" "240e:1:1::1" "240e:1:1::1" "240e:1:1::1" "2408:80f0:0:1::1" "2408:80f0:0:1::1" "2408:80f0:0:1::1" "2409:8c00:8421:1304::5" "2409:8c00:8421:1304::5" "2409:8c00:8421:1304::5")
declare -a DNS_IPV6_SECONDARY_ISP=("240e:1:1::2" "240e:1:1::2" "240e:1:1::2" "240e:1:1::2" "2408:80f0:0:1::2" "2408:80f0:0:1::2" "2408:80f0:0:1::2" "2409:8c00:8421:1304::6" "2409:8c00:8421:1304::6" "2409:8c00:8421:1304::6")

# 特殊 DNS
declare -a DNS_NAME_SPECIAL=("AdGuard DNS" "AdGuard 家庭" "NextDNS" "Control D" "V2EX DNS" "Dyn DNS" "Hurricane Electric" "Level3" "Freenom DNS" "Comodo DNS")
declare -a DNS_PRIMARY_SPECIAL=("94.140.14.14" "94.140.14.15" "45.90.28.0" "76.76.2.0" "199.91.73.222" "216.146.35.35" "74.82.42.42" "4.2.2.1" "80.80.80.80" "8.26.56.26")
declare -a DNS_SECONDARY_SPECIAL=("94.140.15.15" "94.140.15.16" "45.90.30.0" "76.76.10.0" "178.79.131.110" "216.146.36.36" "2001:470:20::2" "4.2.2.2" "80.80.81.81" "8.20.247.20")
declare -a DNS_DESC_SPECIAL=("去廣告" "去廣告 + 家庭" "可定制" "可配置" "社區運營" "Oracle 旗下" "IPv6 先驅" "美國骨干" "免費域名" "安全 DNS")
declare -a DNS_IPV6_SPECIAL=("2a10:50c0::1:ff" "2a10:50c0::2:ff" "2a10:50c0::1:ff" "2a10:50c0::1:ff" "2a10:50c0::1:ff" "2001:470:20::2" "2001:470:20::2" "2001:1900:2254:2102::5" "2001:1900:2254:2102::5" "2001:1900:2254:2102::5")
declare -a DNS_IPV6_SECONDARY_SPECIAL=("2a10:50c0::2:ff" "2a10:50c0::1:ff" "2a10:50c0::2:ff" "2a10:50c0::2:ff" "2a10:50c0::2:ff" "2001:470:20::2" "2001:470:20::2" "2001:1900:2254:2102::5" "2001:1900:2254:2102::5" "2001:1900:2254:2102::5")

# ==================== 獲取 DNS 信息 ====================
get_dns_info() {
    local i=$1 name="" primary="" secondary="" desc="" primary_v6="" secondary_v6=""
    
    if [[ $i -lt 15 ]]; then
        # 國內 DNS
        name="${DNS_NAME_CN[$i]}"
        primary="${DNS_PRIMARY_CN[$i]}"
        secondary="${DNS_SECONDARY_CN[$i]}"
        desc="${DNS_DESC_CN[$i]}"
        primary_v6="${DNS_IPV6_CN[$i]}"
        secondary_v6="${DNS_IPV6_SECONDARY_CN[$i]}"
    elif [[ $i -lt 30 ]]; then
        # 國際 DNS
        local idx=$((i-15))
        name="${DNS_NAME_INT[$idx]}"
        primary="${DNS_PRIMARY_INT[$idx]}"
        secondary="${DNS_SECONDARY_INT[$idx]}"
        desc="${DNS_DESC_INT[$idx]}"
        primary_v6="${DNS_IPV6_INT[$idx]}"
        secondary_v6="${DNS_IPV6_SECONDARY_INT[$idx]}"
    elif [[ $i -lt 40 ]]; then
        # ISP DNS
        local idx=$((i-30))
        name="${DNS_NAME_ISP[$idx]}"
        primary="${DNS_PRIMARY_ISP[$idx]}"
        secondary="${DNS_SECONDARY_ISP[$idx]}"
        desc="${DNS_DESC_ISP[$idx]}"
        primary_v6="${DNS_IPV6_ISP[$idx]}"
        secondary_v6="${DNS_IPV6_SECONDARY_ISP[$idx]}"
    else
        # 特殊 DNS
        local idx=$((i-40))
        name="${DNS_NAME_SPECIAL[$idx]}"
        primary="${DNS_PRIMARY_SPECIAL[$idx]}"
        secondary="${DNS_SECONDARY_SPECIAL[$idx]}"
        desc="${DNS_DESC_SPECIAL[$idx]}"
        primary_v6="${DNS_IPV6_SPECIAL[$idx]}"
        secondary_v6="${DNS_IPV6_SECONDARY_SPECIAL[$idx]}"
    fi
    
    echo "$name|$primary|$secondary|$desc|$primary_v6|$secondary_v6"
}

# ==================== DNS 速度測試 ====================
test_single_dns() {
    local dns_ip="$1"
    local timeout=$DNS_TEST_TIMEOUT
    local result=""
    local is_ipv6=0
    local total_time=0
    local success_count=0
    
    # 檢測是否為 IPv6 地址
    if [[ "$dns_ip" == *":"* ]]; then
        is_ipv6=1
        
        # 根據 IP 模式跳過測試
        if [[ "$IP_MODE" == "ipv4" ]]; then
            echo "9999"
            return 0
        fi
    else
        # 根據 IP 模式跳過測試
        if [[ "$IP_MODE" == "ipv6" ]]; then
            echo "9999"
            return 0
        fi
    fi
    
    # 使用 dig 測試（多次測試取平均）
    if command -v dig &> /dev/null; then
        for ((n=0; n<DNS_TEST_COUNT; n++)); do
            if [[ $is_ipv6 -eq 1 ]]; then
                result=$(dig +short +time=$timeout +tries=1 AAAA "$TEST_DOMAIN" @"$dns_ip" 2>/dev/null | head -1) || true
            else
                result=$(dig +short +time=$timeout +tries=1 A "$TEST_DOMAIN" @"$dns_ip" 2>/dev/null | head -1) || true
            fi
            
            if [[ -n "$result" ]]; then
                local time_ms
                time_ms=$(dig +time=$timeout +tries=1 @"$dns_ip" "$TEST_DOMAIN" 2>/dev/null 2>&1 | grep "Query time:" | awk '{print $4}') || true
                if [[ "$time_ms" =~ ^[0-9]+$ ]]; then
                    total_time=$((total_time + time_ms))
                    success_count=$((success_count + 1))
                fi
            fi
        done
        
        if [[ $success_count -gt 0 ]]; then
            echo $((total_time / success_count))
            return 0
        fi
    fi
    
    # 使用 ping 測試
    if [[ $is_ipv6 -eq 1 ]]; then
        if command -v ping6 &> /dev/null; then
            if ping6 -c 1 -W 1 "$dns_ip" &>/dev/null; then
                echo "100"
                return 0
            fi
        fi
    else
        if ping -c 1 -W 1 "$dns_ip" &>/dev/null; then
            echo "100"
            return 0
        fi
    fi
    
    echo "9999"
    return 0
}

# ==================== 監聽跳過按鍵 ====================
listen_for_skip() {
    while true; do
        local key=""
        read -rsn1 key 2>/dev/null || key=""
        if [[ "$key" == "t" || "$key" == "T" ]]; then
            SKIP_TEST=1
            break
        fi
    done
}

# ==================== 測試所有 DNS ====================
test_all_dns() {
    log_info "$(get_text testing) ($(get_text test_domain): $TEST_DOMAIN)"
    log_info "$(get_text press_skip)"
    echo ""
    
    SKIP_TEST=0
    
    # 初始化測試結果數組
    DNS_SPEED_RESULTS=()
    for i in $(seq 0 49); do
        DNS_SPEED_RESULTS[$i]="9999"
    done
    
    # 啟動背景進程監聽跳過按鍵
    listen_for_skip &
    LISTEN_PID=$!
    
    hide_cursor
    
    local total_dns=50
    local tested=0
    
    for i in $(seq 0 49); do
        if [[ $SKIP_TEST -eq 1 ]]; then
            break
        fi
        
        local dns_info=$(get_dns_info $i)
        local dns_name=$(echo "$dns_info" | cut -d'|' -f1)
        local dns_ip=$(echo "$dns_info" | cut -d'|' -f2)
        
        # 根據 IP 模式跳過不適用的 DNS
        if [[ "$IP_MODE" == "ipv4" && "$dns_ip" == *":"* ]]; then
            DNS_SPEED_RESULTS[$i]="9999"
            continue
        fi
        
        if [[ "$IP_MODE" == "ipv6" && "$dns_ip" != *":"* ]]; then
            DNS_SPEED_RESULTS[$i]="9999"
            continue
        fi
        
        tested=$((tested + 1))
        show_progress $tested $total_dns "$dns_name ($dns_ip)"
        
        DNS_SPEED_RESULTS[$i]=$(test_single_dns "$dns_ip")
    done
    
    show_cursor
    kill $LISTEN_PID 2>/dev/null || true
    wait $LISTEN_PID 2>/dev/null || true
    
    printf "\r                                                              \n"
    
    if [[ $SKIP_TEST -eq 1 ]]; then
        log_warn "$(get_text test_skipped)"
        echo ""
        return 0
    fi
    
    log_success "$(get_text complete)"
    echo ""
}

# ==================== 獲取最快 DNS 索引 ====================
get_fastest_dns_index() {
    local min=9999 idx=0
    for i in "${!DNS_SPEED_RESULTS[@]}"; do
        local speed="${DNS_SPEED_RESULTS[$i]}"
        if [[ "$speed" =~ ^[0-9]+$ ]] && [[ "$speed" -lt "$min" ]]; then
            min="$speed"
            idx=$i
        fi
    done
    echo "$idx"
}

# ==================== 顯示 DNS 菜單 ====================
show_dns_menu() {
    local page=$1 dns_type="${2:-standard}"
    local start=$(( (page - 1) * 15 ))
    local end=$((start + 14))
    
    echo ""
    log_header
    echo -e "   ${BOLD_WHITE}$(get_text standard_dns) - $(get_text page) $page/4 [${IP_MODE}, ${DNS_TEST_TIMEOUT}s timeout]${NC}"
    log_header
    echo ""
    
    printf "  ${BOLD}序號${NC}  ${BOLD}服務商${NC}                    ${BOLD}地址${NC}                    ${BOLD}響應時間${NC}      ${BOLD}特點${NC}\n"
    printf "  ────────────────────────────────────────────────────────────────────────────────────────\n"
    
    for i in $(seq $start $end); do
        [[ $i -gt 49 ]] && continue
        local info=$(get_dns_info $i)
        local name=$(echo "$info" | cut -d'|' -f1)
        local primary=$(echo "$info" | cut -d'|' -f2)
        local desc=$(echo "$info" | cut -d'|' -f4)
        local speed="${DNS_SPEED_RESULTS[$i]:-9999}"
        [[ ! "$speed" =~ ^[0-9]+$ ]] && speed="9999"
        
        # 根據速度設置顏色
        local speed_color="$RED"
        [[ "$speed" -le 30 ]] && speed_color="$GREEN"
        [[ "$speed" -gt 30 && "$speed" -le 100 ]] && speed_color="$YELLOW"
        [[ "$speed" -gt 100 && "$speed" -lt 9999 ]] && speed_color="$CYAN"
        
        # 設置標記
        local mark="" sel="  "
        [[ "$i" == "$FASTEST_INDEX" ]] && mark="${BOLD}${GREEN}$(get_text recommended)${NC} "
        [[ "$i" == "$CURRENT_SELECTION" ]] && sel="${GREEN}▶${NC} "
        
        # 設置速度文本
        local speed_txt=""
        [[ "$speed" -ge 9999 ]] && speed_txt="$(get_text timeout)" || speed_txt="${speed}ms"
        
        printf "  ${sel}${YELLOW}%2d${NC}  ${mark}%-25s %-25s ${speed_color}%-15s${NC} %s\n" "$((i+1))" "$name" "$primary" "$speed_txt" "$desc"
    done
    
    printf "  ────────────────────────────────────────────────────────────────────────────────────────\n"
    printf "  $(get_text navigate)\n"
}

# ==================== 鍵盤選擇 DNS ====================
select_dns_keyboard() {
    local dns_type="${1:-standard}"
    CURRENT_SELECTION=0
    CURRENT_PAGE=1
    
    while true; do
        clear
        show_copyright
        log_info "$(get_text step1)"
        show_dns_menu $CURRENT_PAGE "$dns_type"
        
        local key=""
        read -rsn1 key 2>/dev/null || key=""
        
        if [[ "$key" == $'\x1b' ]]; then
            read -rsn2 key2 2>/dev/null || key2=""
            key="$key$key2"
        fi
        
        case "$key" in
            $'\x1b[A')
                CURRENT_SELECTION=$((CURRENT_SELECTION - 1))
                [[ $CURRENT_SELECTION -lt 0 ]] && { CURRENT_SELECTION=49; CURRENT_PAGE=4; }
                [[ $CURRENT_SELECTION -lt $(( (CURRENT_PAGE - 1) * 15 )) ]] && CURRENT_PAGE=$((CURRENT_PAGE - 1))
                ;;
            $'\x1b[B')
                CURRENT_SELECTION=$((CURRENT_SELECTION + 1))
                [[ $CURRENT_SELECTION -gt 49 ]] && { CURRENT_SELECTION=0; CURRENT_PAGE=1; }
                [[ $CURRENT_SELECTION -gt $(( CURRENT_PAGE * 15 - 1 )) ]] && CURRENT_PAGE=$((CURRENT_PAGE + 1))
                ;;
            $'\x1b[D')
                CURRENT_PAGE=$((CURRENT_PAGE - 1))
                [[ $CURRENT_PAGE -lt 1 ]] && CURRENT_PAGE=4
                [[ $CURRENT_SELECTION -gt $(( CURRENT_PAGE * 15 - 1 )) ]] && CURRENT_SELECTION=$(( (CURRENT_PAGE - 1) * 15 ))
                ;;
            $'\x1b[C')
                CURRENT_PAGE=$((CURRENT_PAGE + 1))
                [[ $CURRENT_PAGE -gt 4 ]] && CURRENT_PAGE=1
                [[ $CURRENT_SELECTION -lt $(( (CURRENT_PAGE - 1) * 15 )) ]] && CURRENT_SELECTION=$(( (CURRENT_PAGE - 1) * 15 ))
                ;;
            '')
                local info=$(get_dns_info $CURRENT_SELECTION)
                local name=$(echo "$info" | cut -d'|' -f1)
                local primary=$(echo "$info" | cut -d'|' -f2)
                local secondary=$(echo "$info" | cut -d'|' -f3)
                SELECTED_DNS="$primary,$secondary"
                SELECTED_DNS_NAME="$name"
                SELECTED_DNS_TYPE="standard"
                echo ""
                log_success "$(get_text selected): ${GREEN}${SELECTED_DNS_NAME}${NC}"
                return 0
                ;;
            '0')
                echo ""
                printf "  $(get_text enter_primary): "; read ip1
                printf "  $(get_text enter_secondary): "; read ip2
                if [[ -n "$ip1" && -n "$ip2" ]]; then
                    SELECTED_DNS="$ip1,$ip2"
                elif [[ -n "$ip1" ]]; then
                    SELECTED_DNS="$ip1,8.8.8.8"
                else
                    log_warn "$(get_text invalid_input)"
                    sleep 1
                    continue
                fi
                SELECTED_DNS_NAME="$(get_text custom)"
                SELECTED_DNS_TYPE="standard"
                log_success "$(get_text selected): ${GREEN}$(get_text custom)${NC}"
                return 0
                ;;
            'q'|'Q')
                SELECTED_DNS=""; SELECTED_DNS_NAME=""
                return 0
                ;;
        esac
    done
}

# ==================== 配置 systemd-resolved ====================
configure_systemd_resolved() {
    local dns_servers="$1"
    local dns_v6_servers="$2"
    local conf="/etc/systemd/resolved.conf"
    
    # 備份原配置
    backup_current_config
    
    cp "$conf" "${conf}.bak.$(date +%Y%m%d%H%M%S)" 2>/dev/null || true
    
    # 創建配置目錄
    mkdir -p /etc/systemd/resolved.conf.d 2>/dev/null || true
    
    # 根據 IP 模式構建配置
    local dns_line=""
    if [[ "$IP_MODE" == "ipv4" ]]; then
        dns_line="DNS=$dns_servers"
    elif [[ "$IP_MODE" == "ipv6" ]]; then
        dns_line="DNS=$dns_v6_servers"
    else  # dual stack
        dns_line="DNS=$dns_servers $dns_v6_servers"
    fi
    
    # 寫入新配置
    cat > "$conf" << EOF
[Resolve]
$dns_line
FallbackDNS=1.1.1.1 8.8.4.4 2606:4700:4700::1111 2001:4860:4860::8888
DNSStubListener=yes
DNSOverTLS=no
Cache=yes
EOF
    
    # 確保 systemd-resolved 服務運行
    log_info "正在啟動 systemd-resolved 服務..."
    systemctl enable systemd-resolved 2>/dev/null || true
    systemctl restart systemd-resolved 2>/dev/null || true
    sleep 2
    
    # 正確處理 /etc/resolv.conf
    if [[ -L /etc/resolv.conf ]]; then
        rm -f /etc/resolv.conf
    elif [[ -f /etc/resolv.conf ]]; then
        cp /etc/resolv.conf /etc/resolv.conf.bak.$(date +%Y%m%d%H%M%S) 2>/dev/null || true
        rm -f /etc/resolv.conf
    fi
    
    # 創建符號鏈接
    ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf 2>/dev/null || \
    ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf 2>/dev/null || \
    ln -sf /usr/lib/systemd/resolv.conf /etc/resolv.conf 2>/dev/null
    
    # 如果符號鏈接創建失敗，直接寫入文件
    if [[ ! -e /etc/resolv.conf ]]; then
        cat > /etc/resolv.conf << EOF
# DNS 配置 - $(date)
# IP 模式：$IP_MODE
# 作者：程星噠 (B 站：1765875510)
# 贊助商：千問 AI | 轉轉二手
EOF
        if [[ "$IP_MODE" != "ipv6" && -n "$dns_servers" ]]; then
            echo "nameserver $(echo $dns_servers | tr ',' '\n' | head -1)" >> /etc/resolv.conf
            local dns2=$(echo $dns_servers | tr ',' '\n' | tail -1)
            [[ "$dns2" != "$(echo $dns_servers | tr ',' '\n' | head -1)" ]] && echo "nameserver $dns2" >> /etc/resolv.conf
        fi
        if [[ "$IP_MODE" != "ipv4" && -n "$dns_v6_servers" ]]; then
            echo "nameserver $(echo $dns_v6_servers | tr ',' '\n' | head -1)" >> /etc/resolv.conf
        fi
        echo "options timeout:2 attempts:3 rotate" >> /etc/resolv.conf
        chmod 644 /etc/resolv.conf
    fi
    
    log_success "systemd-resolved 配置完成 (模式：$IP_MODE)"
    
    if [[ $TAILSCALE_ACTIVE -eq 1 ]]; then
        log_warn "Tailscale 可能會覆蓋 DNS 配置，建議執行："
        echo -e "  ${CYAN}sudo tailscale set --accept-dns=false${NC}"
    fi
}

# ==================== 配置 resolv.conf ====================
configure_resolv_conf() {
    local dns_servers="$1"
    local dns_v6_servers="$2"
    
    # 備份當前配置
    backup_current_config
    
    # 檢查 Tailscale
    if grep -q "tailscale" /etc/resolv.conf 2>/dev/null; then
        log_warn "檢測到 Tailscale，將使用 systemd-resolved 配置"
        configure_systemd_resolved "$dns_servers" "$dns_v6_servers"
        return
    fi
    
    # 處理現有的 /etc/resolv.conf
    if [[ -L /etc/resolv.conf ]]; then
        local link_target=$(readlink /etc/resolv.conf)
        rm -f /etc/resolv.conf
        # 如果是 systemd-resolved 的鏈接，使用 systemd-resolved 配置
        if [[ "$link_target" == *"systemd"* ]] || [[ "$link_target" == *"resolved"* ]]; then
            configure_systemd_resolved "$dns_servers" "$dns_v6_servers"
            return
        fi
    elif [[ -f /etc/resolv.conf ]]; then
        cp /etc/resolv.conf /etc/resolv.conf.bak.$(date +%Y%m%d%H%M%S) 2>/dev/null || true
    fi
    
    # 根據 IP 模式寫入配置
    cat > /etc/resolv.conf << EOF
# DNS 配置 - $(date)
# IP 模式：$IP_MODE
# 作者：程星噠 (B 站：1765875510)
# 贊助商：千問 AI | 轉轉二手
EOF
    
    if [[ "$IP_MODE" != "ipv6" && -n "$dns_servers" ]]; then
        local dns1=$(echo $dns_servers | tr ',' ' ' | awk '{print $1}')
        local dns2=$(echo $dns_servers | tr ',' ' ' | awk '{print $2}')
        echo "nameserver $dns1" >> /etc/resolv.conf
        [[ -n "$dns2" && "$dns2" != "$dns1" ]] && echo "nameserver $dns2" >> /etc/resolv.conf
    fi
    
    if [[ "$IP_MODE" != "ipv4" && -n "$dns_v6_servers" ]]; then
        local dns_v6_1=$(echo $dns_v6_servers | tr ',' ' ' | awk '{print $1}')
        local dns_v6_2=$(echo $dns_v6_servers | tr ',' ' ' | awk '{print $2}')
        echo "nameserver $dns_v6_1" >> /etc/resolv.conf
        [[ -n "$dns_v6_2" && "$dns_v6_2" != "$dns_v6_1" ]] && echo "nameserver $dns_v6_2" >> /etc/resolv.conf
    fi
    
    echo "options timeout:2 attempts:3 rotate" >> /etc/resolv.conf
    chmod 644 /etc/resolv.conf
    
    log_success "resolv.conf 配置完成 (模式：$IP_MODE)"
}

# ==================== 驗證 DNS 配置 ====================
verify_dns() {
    log_info "$(get_text verify)..."
    echo ""
    
    # 檢查 /etc/resolv.conf 是否存在
    if [[ ! -e /etc/resolv.conf ]]; then
        log_warn "/etc/resolv.conf 不存在，嘗試重新創建..."
        configure_resolv_conf "$FINAL_DNS" "$FINAL_DNS_V6"
    fi
    
    # 顯示配置
    echo -e "${CYAN}當前 /etc/resolv.conf 配置：${NC}"
    log_subheader
    if [[ -e /etc/resolv.conf ]]; then
        cat /etc/resolv.conf
    else
        log_warn "無法讀取 /etc/resolv.conf"
    fi
    echo ""
    
    # 使用 dig 或 nslookup 測試 DNS
    local test_success=0
    
    if command -v dig &> /dev/null; then
        if dig +short +time=2 +tries=1 "$TEST_DOMAIN" &>/dev/null; then
            log_success "$(get_text verify_success)"
            test_success=1
        fi
    elif command -v nslookup &> /dev/null; then
        if nslookup "$TEST_DOMAIN" &>/dev/null; then
            log_success "$(get_text verify_success)"
            test_success=1
        fi
    elif ping -c 1 -W 2 "$TEST_DOMAIN" &>/dev/null; then
        log_success "$(get_text verify_success)"
        test_success=1
    fi
    
    if [[ $test_success -eq 0 ]]; then
        log_warn "$(get_text verify_failed)"
        return 1
    fi
    
    return 0
}

# ==================== 查看當前配置 ====================
view_current_config() {
    echo ""
    log_header
    echo -e "   ${BOLD_WHITE}當前 DNS 配置${NC}"
    log_header
    echo ""
    
    if [[ -e /etc/resolv.conf ]]; then
        echo -e "${CYAN}/etc/resolv.conf:${NC}"
        cat /etc/resolv.conf
        echo ""
    fi
    
    if [[ -e /etc/systemd/resolved.conf ]]; then
        echo -e "${CYAN}/etc/systemd/resolved.conf:${NC}"
        cat /etc/systemd/resolved.conf
        echo ""
    fi
    
    log_header
}

# ==================== 主函數 ====================
main() {
    # 顯示作者信息和贊助商
    show_author_info
    show_sponsor_banner
    
    # 選擇語言
    select_language
    
    # 檢查管道執行
    check_pipe
    
    # 顯示版權信息
    show_copyright
    
    # 檢查 root 權限
    check_root
    
    # 檢測系統信息
    detect_os
    detect_network_manager
    get_active_interface
    
    echo ""
    
    # 檢測 Tailscale
    check_tailscale
    
    # 獲取服務器信息
    get_server_info
    
    # 選擇 IP 模式
    select_ip_mode
    
    # 處理 Tailscale
    handle_tailscale
    
    # 測試 DNS 速度
    test_all_dns
    
    # 獲取最快的 DNS
    FASTEST_INDEX=$(get_fastest_dns_index)
    
    if [[ $SKIP_TEST -eq 0 ]]; then
        local fastest_info=$(get_dns_info $FASTEST_INDEX)
        local fastest_name=$(echo "$fastest_info" | cut -d'|' -f1)
        local fastest_ip=$(echo "$fastest_info" | cut -d'|' -f2)
        log_success "$(get_text fastest): ${GREEN}${fastest_name}${NC} (${fastest_ip})"
    else
        log_info "使用默認推薦：${GREEN}阿里 DNS (223.5.5.5)${NC}"
        FASTEST_INDEX=0
    fi
    
    # 選擇首選 DNS
    SELECTED_DNS_TYPE="standard"
    select_dns_keyboard "$SELECTED_DNS_TYPE"
    
    PRIMARY_DNS="$SELECTED_DNS"
    PRIMARY_NAME="$SELECTED_DNS_NAME"
    PRIMARY_IP=$(echo $PRIMARY_DNS | cut -d',' -f1)
    
    # 獲取 IPv6 DNS
    local info=$(get_dns_info $CURRENT_SELECTION)
    PRIMARY_IP_V6=$(echo "$info" | cut -d'|' -f5)
    
    log_info "$(get_text primary): ${GREEN}${PRIMARY_NAME}${NC} ($PRIMARY_IP)"
    if [[ -n "$PRIMARY_IP_V6" && "$IP_MODE" != "ipv4" ]]; then
        log_info "$(get_text v6_address): ${GREEN}${PRIMARY_IP_V6}${NC}"
    fi
    
    echo ""
    
    # 選擇備用 DNS
    printf "$(get_text set_secondary) "; read use_secondary
    
    SECONDARY_DNS=""
    SECONDARY_IP_V6=""
    if [[ "$use_secondary" == "y" || "$use_secondary" == "Y" ]]; then
        select_dns_keyboard "$SELECTED_DNS_TYPE"
        SECONDARY_DNS="$SELECTED_DNS"
        info=$(get_dns_info $CURRENT_SELECTION)
        SECONDARY_IP_V6=$(echo "$info" | cut -d'|' -f5)
    else
        log_info "$(get_text skip_secondary)"
    fi
    
    # 構建最終 DNS 配置
    if [[ "$IP_MODE" == "ipv4" ]]; then
        if [[ -z "$SECONDARY_DNS" ]]; then
            FINAL_DNS="$PRIMARY_IP"
            FINAL_DNS_V6=""
        else
            SECONDARY_IP=$(echo $SECONDARY_DNS | cut -d',' -f1)
            FINAL_DNS="$PRIMARY_IP,$SECONDARY_IP"
            FINAL_DNS_V6=""
        fi
    elif [[ "$IP_MODE" == "ipv6" ]]; then
        if [[ -z "$PRIMARY_IP_V6" ]]; then
            log_warn "所選 DNS 不支持 IPv6，使用 Cloudflare IPv6"
            PRIMARY_IP_V6="2606:4700:4700::1111"
        fi
        if [[ -z "$SECONDARY_IP_V6" ]]; then
            FINAL_DNS=""
            FINAL_DNS_V6="$PRIMARY_IP_V6"
        else
            FINAL_DNS=""
            FINAL_DNS_V6="$PRIMARY_IP_V6,$SECONDARY_IP_V6"
        fi
    else  # dual stack
        if [[ -z "$SECONDARY_DNS" ]]; then
            FINAL_DNS="$PRIMARY_IP"
        else
            SECONDARY_IP=$(echo $SECONDARY_DNS | cut -d',' -f1)
            FINAL_DNS="$PRIMARY_IP,$SECONDARY_IP"
        fi
        if [[ -n "$PRIMARY_IP_V6" ]]; then
            if [[ -n "$SECONDARY_IP_V6" ]]; then
                FINAL_DNS_V6="$PRIMARY_IP_V6,$SECONDARY_IP_V6"
            else
                FINAL_DNS_V6="$PRIMARY_IP_V6"
            fi
        else
            FINAL_DNS_V6="2606:4700:4700::1111"
        fi
    fi
    
    echo ""
    log_info "$(get_text final): ${CYAN}${FINAL_DNS}${FINAL_DNS_V6:+ | $FINAL_DNS_V6}${NC}"
    printf "$(get_text confirm_config) "; read confirm
    
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
        log_warn "$(get_text cancelled)"
        exit 0
    fi
    
    echo ""
    log_info "$(get_text configuring)..."
    
    # 根據網絡管理器選擇配置方式
    case $NETWORK_MANAGER in
        netplan|networkmanager|systemd-networkd)
            configure_systemd_resolved "$FINAL_DNS" "$FINAL_DNS_V6"
            ;;
        *)
            configure_resolv_conf "$FINAL_DNS" "$FINAL_DNS_V6"
            ;;
    esac
    
    # 驗證 DNS 配置
    verify_dns
    
    echo ""
    log_header
    log_success "$(get_text success)"
    log_header
    
    # 顯示作者結束信息
    show_author_end
    
    echo "$(get_text thanks)"
    echo ""
}

# ==================== 程序入口 ====================
main "$@"