#!/bin/bash

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

# 日志函数 (信息性日志输出到 stderr)
log() {
    echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')] $1${NC}" >&2
}

log_success() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] $1${NC}" >&2
}

log_warning() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] $1${NC}" >&2
}

# 错误日志函数 (保持输出到 stderr)
log_error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] $1${NC}" >&2
}

# NTP服务器列表
NTP_SERVERS_CN=(
    "ntp.aliyun.com"
    "ntp1.aliyun.com"
    "ntp2.aliyun.com"
    "ntp3.aliyun.com"
    "ntp4.aliyun.com"
    "ntp5.aliyun.com"
    "ntp6.aliyun.com"
    "ntp7.aliyun.com"
    "ntp.tencent.com"
    "ntp1.tencent.com"
    "ntp2.tencent.com"
    "ntp3.tencent.com"
    "ntp4.tencent.com"
    "ntp5.tencent.com"
    "cn.ntp.org.cn"
    "ntp.ntsc.ac.cn"
)
NTP_SERVERS_GLOBAL=("time.cloudflare.com" "time.google.com" "pool.ntp.org" "time.windows.com")

# 检测是否在中国
detect_location() {
    log "正在检测服务器地理位置..."
    local cn_delay=9999
    local global_delay=9999

    for server in www.baidu.com www.taobao.com www.qq.com; do
        local delay=$(timeout 2 ping -c 3 -q $server 2>/dev/null | grep -oP 'rtt min/avg/max/mdev = \d+\.\d+/(\d+\.\d+)' | cut -d '/' -f 2)
        if [[ ! -z "$delay" && $(echo "$delay < $cn_delay" | bc -l) -eq 1 ]]; then cn_delay=$delay; fi
        sleep 0.1
    done
    for server in www.google.com www.cloudflare.com www.github.com; do
        local delay=$(timeout 2 ping -c 3 -q $server 2>/dev/null | grep -oP 'rtt min/avg/max/mdev = \d+\.\d+/(\d+\.\d+)' | cut -d '/' -f 2)
        if [[ ! -z "$delay" && $(echo "$delay < $global_delay" | bc -l) -eq 1 ]]; then global_delay=$delay; fi
        sleep 0.1
    done

    log "中国服务器最低平均延迟: ${cn_delay}ms"
    log "国际服务器最低平均延迟: ${global_delay}ms"

    if [[ $(echo "$cn_delay == 9999" | bc -l) -eq 1 && $(echo "$global_delay == 9999" | bc -l) -eq 1 ]]; then
        log_warning "Ping 测试失败，尝试使用 HTTP 请求检测..."
        local cn_reachable=0; local global_reachable=0
        if curl -s --connect-timeout 3 https://www.baidu.com -o /dev/null; then cn_reachable=1; cn_delay=100; fi
        if curl -s --connect-timeout 3 https://www.cloudflare.com -o /dev/null; then global_reachable=1; global_delay=100; fi

        if [[ $cn_reachable -eq 0 && $global_reachable -eq 0 ]]; then
             log_warning "无法确定地理位置 (Ping 和 HTTP 均失败)，默认使用中国NTP服务器"
             echo "CN"; return
        elif [[ $cn_reachable -eq 1 && $global_reachable -eq 0 ]]; then
            log_success "检测到服务器位于中国 (基于 HTTP)"
            echo "CN"; return
        elif [[ $cn_reachable -eq 0 && $global_reachable -eq 1 ]]; then
            log_success "检测到服务器位于海外 (基于 HTTP)"
            echo "GLOBAL"; return
        fi
         log_warning "HTTP 测试均成功，依赖 Ping 结果或判断为海外"
    fi

    if [[ $(echo "$cn_delay == 9999" | bc -l) -eq 1 && $(echo "$global_delay == 9999" | bc -l) -eq 1 ]]; then
        log_warning "无法确定地理位置，默认使用中国NTP服务器"
        echo "CN"; return
    fi

    if [[ $(echo "$cn_delay < $global_delay * 1.5" | bc -l) -eq 1 ]]; then
        log_success "检测到服务器位于中国 (基于 Ping/HTTP 延迟)"
        echo "CN"
    else
        log_success "检测到服务器位于海外 (基于 Ping/HTTP 延迟)"
        echo "GLOBAL"
    fi
}

# 设置时区为上海
set_timezone() {
    log "设置时区为 Asia/Shanghai..."
    if timedatectl set-timezone Asia/Shanghai &>/dev/null; then
        log_success "成功设置时区为 Asia/Shanghai (使用 timedatectl)"
    elif [ -L /etc/localtime ] && [ -f /usr/share/zoneinfo/Asia/Shanghai ]; then
        log "尝试通过更新软链接设置时区..."
        if ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime; then
            log_success "使用软链接设置时区为 Asia/Shanghai"
            if [ -f /etc/timezone ]; then echo "Asia/Shanghai" > /etc/timezone; log "更新 /etc/timezone 文件"; fi
        else log_error "设置时区失败 (更新软链接失败)"; return 1; fi
    elif [ ! -e /etc/localtime ] && [ -f /usr/share/zoneinfo/Asia/Shanghai ]; then
         log "尝试通过创建软链接设置时区..."
         if ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime; then
            log_success "使用软链接设置时区为 Asia/Shanghai"
             if [ -f /etc/timezone ]; then echo "Asia/Shanghai" > /etc/timezone; log "更新 /etc/timezone 文件"; fi
         else log_error "设置时区失败 (创建软链接失败)"; return 1; fi
    else log_error "无法设置时区 (不支持 timedatectl 且无法处理 /etc/localtime)"; return 1; fi

    sleep 1
    current_tz=$(date +%Z)
    if [[ "$current_tz" == "CST" ]]; then
        log_success "时区设置验证成功：$current_tz"
    else
        log_warning "时区验证可能不准确或未生效：当前为 $current_tz (预期 CST)"
        if command -v timedatectl &>/dev/null; then
           local tz_check=$(timedatectl status | grep "Time zone:")
           log "timedatectl 报告: $tz_check"
        fi
    fi
    return 0
}

# 检测时间同步服务 (Updated Order with ntpsec)
detect_time_service() {
    log "检测系统时间同步服务..."

    # 1. systemd-timesyncd
    if systemctl is-active --quiet systemd-timesyncd; then
        log_success "检测到 systemd-timesyncd 服务正在运行"
        echo "systemd-timesyncd"; return
    fi
    # 2. chrony/chronyd
    if systemctl is-active --quiet chronyd || systemctl is-active --quiet chrony; then
        log_success "检测到 chrony/chronyd 服务正在运行"
        echo "chronyd"; return #统一返回chronyd
    fi
    # 3. ntpsec
    if systemctl is-active --quiet ntpsec; then
        log_success "检测到 ntpsec 服务正在运行"
        echo "ntpsec"; return
    fi
    # 4. ntp/ntpd
    if systemctl is-active --quiet ntpd || systemctl is-active --quiet ntp; then
        log_success "检测到 ntpd/ntp 服务正在运行"
        echo "ntpd"; return # 统一返回 ntpd for legacy
    fi

    # --- Check enabled but inactive ---
    log "未检测到活动的时间服务，检查已启用的服务..."
    if systemctl is-enabled --quiet systemd-timesyncd; then
         log_warning "检测到 systemd-timesyncd 服务已启用但未运行"
         echo "systemd-timesyncd"; return
    fi
    if systemctl is-enabled --quiet chronyd || systemctl is-enabled --quiet chrony; then
         log_warning "检测到 chrony/chronyd 服务已启用但未运行"
         echo "chronyd"; return
    fi
     if systemctl is-enabled --quiet ntpsec; then
        log_warning "检测到 ntpsec 服务已启用但未运行"
        echo "ntpsec"; return
    fi
    if systemctl is-enabled --quiet ntpd || systemctl is-enabled --quiet ntp; then
         log_warning "检测到 ntpd/ntp 服务已启用但未运行"
         echo "ntpd"; return
    fi

    # --- Fallback ---
    if command -v timedatectl &>/dev/null; then
        log_warning "未检测到特定时间同步服务，但系统支持 systemd，将尝试使用 systemd-timesyncd"
        echo "systemd-timesyncd"
    else
        log_error "无法检测到支持的时间同步服务 (systemd/chrony/ntpsec/ntp)"
        echo "unknown"
    fi
}


# 停止并禁用其他 NTP 服务 (Updated with ntpsec)
stop_other_ntp_services() {
    local service_to_keep=$1 # Expected: systemd-timesyncd, chronyd, ntpsec, ntpd
    log "确保只有一个 NTP 服务运行 ($service_to_keep)..."

    # systemd-timesyncd
    if [[ "$service_to_keep" != "systemd-timesyncd" ]] && systemctl list-unit-files | grep -q systemd-timesyncd.service; then
        if systemctl is-active --quiet systemd-timesyncd; then log "停止 systemd-timesyncd..."; systemctl stop systemd-timesyncd || log_warning "停止 systemd-timesyncd 失败"; fi
        if systemctl is-enabled --quiet systemd-timesyncd; then log "禁用 systemd-timesyncd..."; systemctl disable systemd-timesyncd || log_warning "禁用 systemd-timesyncd 失败"; fi
    fi

    # chrony/chronyd
    local chrony_service_name=$(systemctl list-unit-files --full -all | grep -Eo 'chrony(d)?\.service' | head -n 1)
    if [[ "$service_to_keep" != "chronyd" && -n "$chrony_service_name" ]]; then
         if systemctl is-active --quiet $chrony_service_name; then log "停止 $chrony_service_name..."; systemctl stop $chrony_service_name || log_warning "停止 $chrony_service_name 失败"; fi
         if systemctl is-enabled --quiet $chrony_service_name; then log "禁用 $chrony_service_name..."; systemctl disable $chrony_service_name || log_warning "禁用 $chrony_service_name 失败"; fi
    fi

    # ntpsec
    if [[ "$service_to_keep" != "ntpsec" ]] && systemctl list-unit-files | grep -q ntpsec.service; then
         if systemctl is-active --quiet ntpsec.service; then log "停止 ntpsec.service..."; systemctl stop ntpsec.service || log_warning "停止 ntpsec.service 失败"; fi
         if systemctl is-enabled --quiet ntpsec.service; then log "禁用 ntpsec.service..."; systemctl disable ntpsec.service || log_warning "禁用 ntpsec.service 失败"; fi
    fi

    # ntp/ntpd (Legacy)
    local ntp_service_name=$(systemctl list-unit-files --full -all | grep -Eo 'ntp(d)?\.service' | head -n 1)
    # Avoid stopping ntpsec if ntp/ntpd is an alias for it
    local is_alias_for_ntpsec=false
    if [ -n "$ntp_service_name" ]; then
        local target_file=$(systemctl show -p FragmentPath $ntp_service_name | cut -d= -f2)
        if [ -L "$target_file" ] && [[ "$(readlink -f $target_file)" == *ntpsec.service ]]; then
            is_alias_for_ntpsec=true
        fi
    fi

    if [[ "$service_to_keep" != "ntpd" && -n "$ntp_service_name" && "$is_alias_for_ntpsec" == "false" ]]; then
        if systemctl is-active --quiet $ntp_service_name; then log "停止 $ntp_service_name..."; systemctl stop $ntp_service_name || log_warning "停止 $ntp_service_name 失败"; fi
        if systemctl is-enabled --quiet $ntp_service_name; then log "禁用 $ntp_service_name..."; systemctl disable $ntp_service_name || log_warning "禁用 $ntp_service_name 失败"; fi
    fi
}


# 配置 systemd-timesyncd
configure_systemd_timesyncd() {
    local ntp_servers_str="$1"
    log "配置 systemd-timesyncd..."
    stop_other_ntp_services "systemd-timesyncd"

    if ! command -v timedatectl &>/dev/null; then log_error "timedatectl 命令未找到"; return 1; fi
    if ! systemctl list-unit-files | grep -q systemd-timesyncd.service; then log_error "systemd-timesyncd 服务文件未找到"; return 1; fi

    local config_dir="/etc/systemd"; local config_file="/etc/systemd/timesyncd.conf"
    local config_dropin_dir="/etc/systemd/timesyncd.conf.d"; local dropin_file="${config_dropin_dir}/99-custom-ntp.conf"
    mkdir -p "$config_dir"; mkdir -p "$config_dropin_dir"

    log "在 $dropin_file 中配置 NTP 服务器 (覆盖写入)..."
    cat > "$dropin_file" << EOF
# Configuration generated by setup_time.sh on $(date)
[Time]
NTP=$ntp_servers_str
FallbackNTP=pool.ntp.org time.windows.com time.google.com
EOF
    if [ -f "$config_file" ]; then
        if [ ! -f "${config_file}.bak.$(date +%Y%m%d)" ]; then cp "$config_file" "${config_file}.bak.$(date +%Y%m%d)"; log "已备份主配置文件"; fi
        sed -i -E 's/^(\s*NTP\s*=.*)/#\1/; s/^(\s*FallbackNTP\s*=.*)/#\1/' "$config_file"
        log "已注释掉 $config_file 中的 NTP/FallbackNTP 行 (如有)"
    fi
    log_success "已更新 systemd-timesyncd 配置"

    log "重新加载 systemd-daemon..."; systemctl daemon-reload
    log "启用 systemd-timesyncd 服务...";
    if ! systemctl enable systemd-timesyncd; then systemctl unmask systemd-timesyncd &>/dev/null; systemctl enable systemd-timesyncd || { log_error "启用 systemd-timesyncd 失败"; return 1; }; fi
    log "重启 systemd-timesyncd 服务...";
    if ! systemctl restart systemd-timesyncd; then log_error "重启 systemd-timesyncd 失败"; journalctl -n 20 -u systemd-timesyncd --no-pager >&2; return 1; fi

    log "等待 systemd-timesyncd 启动..."; sleep 3
    if systemctl is-active --quiet systemd-timesyncd; then log_success "systemd-timesyncd 服务已启动并运行"; return 0;
    else log_error "systemd-timesyncd 服务启动失败"; journalctl -n 50 -u systemd-timesyncd --no-pager >&2; return 1; fi
}

# 配置 chronyd
configure_chronyd() {
    local ntp_servers_str="$1"
    log "配置 chronyd..."
    stop_other_ntp_services "chronyd"

    if ! command -v chronyc &>/dev/null; then
        log_warning "chronyd 未安装，尝试安装..."; local pkg_manager=$(command -v apt-get || command -v yum || command -v dnf || echo "unknown")
         case "$pkg_manager" in *apt-get) apt-get update && apt-get install -y chrony || { log_error "apt 安装 chrony 失败"; return 1; } ;; *yum) yum install -y chrony || { log_error "yum 安装 chrony 失败"; return 1; } ;; *dnf) dnf install -y chrony || { log_error "dnf 安装 chrony 失败"; return 1; } ;; *) log_error "无法安装 chronyd"; return 1 ;; esac
         if ! command -v chronyc &>/dev/null; then log_error "安装 chrony 后仍然找不到 chronyc 命令"; return 1; fi
    fi

    local config_file=""; local chrony_service_name=""
    if [ -f "/etc/chrony.conf" ]; then config_file="/etc/chrony.conf"; chrony_service_name="chrony";
    elif [ -f "/etc/chrony/chrony.conf" ]; then config_file="/etc/chrony/chrony.conf"; chrony_service_name="chrony";
    elif systemctl list-unit-files | grep -q chronyd.service; then config_file="/etc/chrony.conf"; chrony_service_name="chronyd"; fi

    if [ -z "$config_file" ] || [ ! -f "$config_file" ]; then log_error "找不到 chrony 配置文件"; return 1; fi
    log "找到 chrony 配置文件: $config_file, 服务名: $chrony_service_name"
    local backup_file="${config_file}.bak.$(date +%s)"

    log "备份原配置到 $backup_file"; cp "$config_file" "$backup_file" || { log_error "备份失败!"; return 1; }
    log "从配置中移除旧的 server/pool 定义..."; grep -Ev '^\s*(server|pool)\s+' "$backup_file" > "${config_file}.tmp"
    log "准备新的 NTP 服务器列表..."; local server_lines=""
    IFS=' ' read -ra server_array <<< "$ntp_servers_str"; for server in "${server_array[@]}"; do server_lines+="server $server iburst\n"; done
    log "将新的 NTP 服务器写入配置文件..."; awk -v servers="$server_lines" 'BEGIN {print servers} {print}' "${config_file}.tmp" > "$config_file"; rm "${config_file}.tmp"

    if ! grep -q "^makestep" "$config_file"; then echo "makestep 1.0 3" >> "$config_file"; log "添加 'makestep'"; fi
    if ! grep -q "^rtcsync" "$config_file"; then echo "rtcsync" >> "$config_file"; log "添加 'rtcsync'"; fi
    if ! grep -q "^\s*logdir" "$config_file"; then echo "logdir /var/log/chrony" >> "$config_file"; log "添加 'logdir'"; fi
    log_success "已更新 chronyd 配置: $config_file"

    log "启用 $chrony_service_name 服务...";
    if ! systemctl enable "$chrony_service_name"; then systemctl unmask "$chrony_service_name" &>/dev/null; systemctl enable "$chrony_service_name" || { log_error "启用 $chrony_service_name 失败"; return 1; }; fi
    log "重启 $chrony_service_name 服务...";
    if ! systemctl restart "$chrony_service_name"; then log_error "重启 $chrony_service_name 失败"; journalctl -n 20 -u "$chrony_service_name" --no-pager >&2; return 1; fi

    log "等待 $chrony_service_name 启动..."; sleep 5
    if systemctl is-active --quiet "$chrony_service_name"; then
        log_success "$chrony_service_name 服务已启动"
        log "尝试执行 'chronyc makestep'..."; if chronyc -a makestep; then log_success "执行了 'chronyc makestep'"; else log_warning "'chronyc makestep' 失败"; fi
        return 0
    else log_error "$chrony_service_name 服务启动失败"; journalctl -n 50 -u "$chrony_service_name" --no-pager >&2; return 1; fi
}

# 配置 ntpd 或 ntpsec (Updated to handle both)
configure_ntpd() {
    local service_type="$1" # Expected: "ntpd" or "ntpsec"
    local ntp_servers_str="$2"

    log "配置 $service_type..."

    # Determine actual service unit name and config file path
    local service_unit_name=""
    local config_file=""
    local install_pkg=""

    if [[ "$service_type" == "ntpsec" ]]; then
        if systemctl list-unit-files | grep -q ntpsec.service; then
            service_unit_name="ntpsec.service"
            config_file="/etc/ntpsec/ntp.conf" # Default ntpsec path
            # Check if ntpsec package needs ntpdate separately? Usually not.
             install_pkg="ntpsec" # Package name might be ntpsec
        else
            log_error "检测到类型为 ntpsec 但未找到 ntpsec.service 文件"
            # Fallback to check legacy ntp/ntpd just in case detection was wrong
            service_type="ntpd"
        fi
    fi

    # If type is ntpd or fallback from ntpsec check
    if [[ "$service_type" == "ntpd" ]]; then
        if systemctl list-unit-files | grep -q ntpd.service; then service_unit_name="ntpd.service";
        elif systemctl list-unit-files | grep -q ntp.service; then service_unit_name="ntp.service";
        fi
        config_file="/etc/ntp.conf" # Default legacy path
        install_pkg="ntp" # Package name is usually ntp (might need ntpdate too on debian)
    fi

    if [ -z "$service_unit_name" ]; then
        log_warning "无法确定 $service_type 的确切服务单元名，将尝试使用 $install_pkg.service"
         service_unit_name="$install_pkg.service" # Best guess
    fi

    # Check config file existence after determining potential path
    if [ ! -f "$config_file" ]; then
        log_warning "配置文件 $config_file 不存在。尝试备用路径 /etc/ntp.conf..."
        if [ -f "/etc/ntp.conf" ]; then
            config_file="/etc/ntp.conf"
        else
            log_error "主要和备用配置文件 ($config_file, /etc/ntp.conf) 均未找到。"
            # Attempt installation below might create it.
        fi
    fi
    log "将使用服务单元: $service_unit_name 和配置文件: $config_file"

    # Stop other services
    stop_other_ntp_services "$service_type" # Pass the original type 'ntpsec' or 'ntpd'

    # Check/Install packages
    local ntp_pkg_missing=0
    if [[ "$service_type" == "ntpsec" ]]; then
        if ! command -v ntpd &>/dev/null; then ntp_pkg_missing=1; fi # ntpsec still uses ntpd binary name
        # ntpsec usually includes ntpdate equivalent functionality or uses timedatectl/chrony for step?
        # We still use ntpdate command below for initial sync, so check/install it.
        if ! command -v ntpdate &>/dev/null; then ntp_pkg_missing=1; fi
    else # legacy ntpd
        if ! command -v ntpd &>/dev/null; then ntp_pkg_missing=1; fi
        if ! command -v ntpdate &>/dev/null; then ntp_pkg_missing=1; fi
    fi

    if [[ $ntp_pkg_missing -eq 1 ]]; then
        log_warning "ntpd 或 ntpdate 命令未找到，尝试安装 $install_pkg 包..."
        local pkg_manager=$(command -v apt-get || command -v yum || command -v dnf || echo "unknown")
        local installed_ntp=0
         case "$pkg_manager" in
             *apt-get) apt-get update && apt-get install -y $install_pkg ntpdate && installed_ntp=1 ;; # Ensure ntpdate for legacy too
             *yum|*dnf) $pkg_manager install -y $install_pkg ntpdate && installed_ntp=1 ;; # Install ntpdate explicitly too
             *) log_error "无法安装 $install_pkg"; return 1 ;;
         esac
         if [[ $installed_ntp -eq 0 ]]; then log_error "安装 $install_pkg/ntpdate 失败"; return 1; fi
         # Re-check commands
         if ! command -v ntpd &>/dev/null || ! command -v ntpdate &>/dev/null; then log_error "安装后仍然找不到 ntpd/ntpdate"; return 1; fi
         # Re-determine service name AFTER install, as install might create the correct one
         if [[ "$service_type" == "ntpsec" ]]; then service_unit_name="ntpsec.service";
         else
             if systemctl list-unit-files | grep -q ntpd.service; then service_unit_name="ntpd.service";
             elif systemctl list-unit-files | grep -q ntp.service; then service_unit_name="ntp.service"; fi
         fi
         log "安装后，确认服务单元为: $service_unit_name"
    fi

    # Ensure config file exists after potential install
    if [ ! -f "$config_file" ]; then
        log_error "配置文件 $config_file 在安装后仍然不存在！"
        return 1
    fi

    local backup_file="${config_file}.bak.$(date +%s)"
    log "备份原配置到 $backup_file"; cp "$config_file" "$backup_file" || { log_error "备份失败!"; return 1; }
    log "从配置中移除旧的 server/pool 定义..."; grep -Ev '^\s*(server|pool)\s+' "$backup_file" > "${config_file}.tmp"
    log "准备新的 NTP 服务器列表..."; local server_lines=""
    IFS=' ' read -ra server_array <<< "$ntp_servers_str"; for server in "${server_array[@]}"; do server_lines+="server $server iburst\n"; done
    log "将新的 NTP 服务器写入配置文件..."; awk -v servers="$server_lines" 'BEGIN {print servers} {print}' "${config_file}.tmp" > "$config_file"; rm "${config_file}.tmp"

    # Add basic config directives if missing
    local drift_dir=$(dirname "$(grep -oP '^\s*driftfile\s+\K\S+' $config_file || echo "/var/lib/ntp")")
    mkdir -p "$drift_dir" # Ensure drift dir exists
    if ! grep -q "^\s*driftfile" "$config_file"; then echo "driftfile ${drift_dir}/ntp.drift" >> "$config_file"; log "添加 driftfile"; fi
    if [[ "$service_type" == "ntpsec" ]]; then # ntpsec uses different default restricts maybe? Check defaults
         if ! grep -q "^\s*restrict default" "$config_file"; then
            echo "" >> "$config_file"; echo "# Basic access restrictions (ntpsec) - generated by script" >> "$config_file"
            echo "restrict default limited kod nomodify notrap nopeer noquery" >> "$config_file"
            echo "restrict source limited kod nomodify notrap" >> "$config_file"
            echo "restrict 127.0.0.1" >> "$config_file"; echo "restrict ::1" >> "$config_file"
            log "添加 ntpsec 推荐的 restrict 配置"
         fi
         if ! grep -q "^\s*logfile" "$config_file"; then echo "logfile /var/log/ntpsec/ntp.log" >> "$config_file"; log "添加 ntpsec logfile"; mkdir -p /var/log/ntpsec; chown ntpsec:ntpsec /var/log/ntpsec || true; fi
    else # legacy ntpd
         if ! grep -q "^\s*restrict default" "$config_file"; then
            echo "" >> "$config_file"; echo "# Basic access restrictions (ntpd) - generated by script" >> "$config_file"
            echo "restrict default nomodify notrap nopeer noquery" >> "$config_file"
            echo "restrict 127.0.0.1" >> "$config_file"; echo "restrict ::1" >> "$config_file"
            log "添加基本的 ntpd restrict 配置"
         fi
         if ! grep -q "^\s*logfile" "$config_file"; then echo "logfile /var/log/ntp.log" >> "$config_file"; log "添加 ntpd logfile"; fi
    fi

    log_success "已更新 $service_type 配置: $config_file"

    # Initial sync with ntpdate
    log "尝试使用 ntpdate 进行初始同步..."; if ntpdate -u -b "${server_array[0]}"; then log_success "ntpdate 初始同步成功"; else log_warning "ntpdate 初始同步失败"; fi

    # Enable and restart the determined service unit
    log "启用 $service_unit_name 服务...";
    if ! systemctl enable "$service_unit_name"; then systemctl unmask "$service_unit_name" &>/dev/null; systemctl enable "$service_unit_name" || { log_error "启用 $service_unit_name 失败"; return 1; }; fi
    log "重启 $service_unit_name 服务...";
    if ! systemctl restart "$service_unit_name"; then log_error "重启 $service_unit_name 失败"; journalctl -n 20 -u "$service_unit_name" --no-pager >&2; return 1; fi

    log "等待 $service_unit_name 启动..."; sleep 5
    if systemctl is-active --quiet "$service_unit_name"; then log_success "$service_unit_name 服务已启动"; return 0;
    else log_error "$service_unit_name 服务启动失败"; journalctl -n 50 -u "$service_unit_name" --no-pager >&2; return 1; fi
}


# 检查依赖项
check_dependencies() {
    local missing=0; local pkgs_to_install=""; local pkg_manager=""
    log "检查所需的依赖项..."
    if command -v apt-get &>/dev/null; then pkg_manager="apt-get"; elif command -v yum &>/dev/null; then pkg_manager="yum"; elif command -v dnf &>/dev/null; then pkg_manager="dnf"; fi

    if ! command -v ping &>/dev/null; then log_warning "ping 未找到..."; if [ "$pkg_manager" == "apt-get" ]; then pkgs_to_install+=" iputils-ping"; else pkgs_to_install+=" iputils"; fi; ((missing++)); fi
    if ! command -v bc &>/dev/null; then log_warning "bc 未找到..."; pkgs_to_install+=" bc"; ((missing++)); fi
    if ! command -v curl &>/dev/null; then log_warning "curl 未找到..."; pkgs_to_install+=" curl"; ((missing++)); fi
    if ! command -v systemctl &>/dev/null; then log_error "systemctl 未找到!"; return 1; fi
    if ! command -v grep &>/dev/null; then log_error "grep 未找到!"; return 1; fi
    if ! command -v sed &>/dev/null; then log_error "sed 未找到!"; return 1; fi
    if ! command -v awk &>/dev/null; then log_error "awk 未找到!"; return 1; fi

    if [ $missing -gt 0 ]; then
        log_warning "有 $missing 个基础依赖项缺失: $pkgs_to_install"; if [ -n "$pkg_manager" ]; then
            log "尝试自动安装依赖..."; case "$pkg_manager" in apt-get) apt-get update && apt-get install -y $pkgs_to_install ;; yum|dnf) $pkg_manager install -y $pkgs_to_install ;; esac
            if [ $? -ne 0 ]; then log_error "自动安装依赖失败: $pkgs_to_install"; return 1; fi
            log_success "依赖项已安装"; local recheck_missing=0
            if ! command -v ping &>/dev/null; then ((recheck_missing++)); fi; if ! command -v bc &>/dev/null; then ((recheck_missing++)); fi; if ! command -v curl &>/dev/null; then ((recheck_missing++)); fi
            if [ $recheck_missing -gt 0 ]; then log_error "安装后依赖项仍然缺失"; return 1; fi
        else log_error "无法确定包管理器，请手动安装: $pkgs_to_install"; return 1; fi
    fi
    log_success "所有基本依赖项已满足"; return 0
}

# 验证时间同步 (Updated for ntpsec logging)
verify_time_sync() {
    local service_type=$1 # systemd-timesyncd, chronyd, ntpsec, ntpd
    log "验证时间同步状态 ($service_type)..."
    local sync_status=1; log "等待 15 秒以便服务同步..."; sleep 15

    # Determine actual service unit name for logging if needed
    local service_unit_name=""
    case "$service_type" in
        systemd-timesyncd) service_unit_name="systemd-timesyncd.service" ;;
        chronyd) service_unit_name=$(systemctl list-units --full -all | grep -Eo 'chrony(d)?\.service' | head -n 1 || echo "chrony.service");;
        ntpsec) service_unit_name="ntpsec.service" ;;
        ntpd) service_unit_name=$(systemctl list-units --full -all | grep -Eo 'ntp(d)?\.service' | head -n 1 || echo "ntp.service");;
        *) service_unit_name="unknown";;
    esac

    case "$service_type" in
        systemd-timesyncd)
            if timedatectl status | grep -q "System clock synchronized: yes"; then log_success "timedatectl: 时钟已同步"; sync_status=0;
            elif timedatectl status | grep -q "NTP service: active"; then log_warning "timedatectl: NTP 服务活跃，可能同步中"; timedatectl show | grep -E 'NTPSynchronized|Frequency' >&2; sync_status=0;
            else log_error "timedatectl 未报告同步/活跃"; timedatectl status >&2; journalctl -n 15 -u "$service_unit_name" --no-pager >&2; fi ;;
        chronyd)
             if chronyc -a tracking | grep -q "Leap status.*Normal"; then log_success "chronyc: Leap status 正常"; sync_status=0;
             else log_warning "chronyc: Leap status 非 Normal"; chronyc -a tracking >&2; chronyc -a sources >&2; journalctl -n 15 -u "$service_unit_name" --no-pager >&2; fi ;;
        ntpsec|ntpd) # ntpq works for both
             if ntpq -p | grep -q -E "^\*"; then log_success "ntpq -p: 找到主同步源 (*)"; sync_status=0;
             elif ntpq -p | grep -q -E "^\+"; then log_success "ntpq -p: 找到备选同步源 (+)"; sync_status=0;
             else log_warning "ntpq -p: 未找到 (*) 或 (+) 源"; ntpq -p >&2; ntpq -rv 0 >&2 || true; journalctl -n 15 -u "$service_unit_name" --no-pager >&2; fi ;;
        *) log_error "无法验证未知服务: $service_type"; return 1 ;;
    esac

    local current_time=$(date)
    if [ $sync_status -eq 0 ]; then log_success "时间同步服务 ($service_type) 活跃/已同步。当前: $current_time";
    else log_error "时间同步服务 ($service_type) 未确认同步。当前: $current_time"; fi
    return $sync_status
}

# 主函数
main() {
    log "====== 开始自动时间同步配置 ======"
    if [ "$(id -u)" -ne 0 ]; then log_error "请使用 root 权限运行"; exit 1; fi
    if ! check_dependencies; then log_error "依赖项检查失败"; exit 1; fi

    local location=$(detect_location)
    local ntp_server_list_str=""
    if [ "$location" == "CN" ]; then ntp_server_list_str="${NTP_SERVERS_CN[*]}"; log "使用中国NTP服务器: $ntp_server_list_str";
    else ntp_server_list_str="${NTP_SERVERS_GLOBAL[*]}"; log "使用全球NTP服务器: $ntp_server_list_str"; fi

    if ! set_timezone; then log_warning "设置时区时遇到问题，继续..."; fi

    local time_service=$(detect_time_service)
    log "检测到的或选择的时间同步服务: $time_service"
    local config_success=1

    case "$time_service" in
        systemd-timesyncd) if configure_systemd_timesyncd "$ntp_server_list_str"; then config_success=0; fi ;;
        chronyd) if configure_chronyd "$ntp_server_list_str"; then config_success=0; fi ;;
        ntpsec) if configure_ntpd "ntpsec" "$ntp_server_list_str"; then config_success=0; fi ;; # Call configure_ntpd with type ntpsec
        ntpd) if configure_ntpd "ntpd" "$ntp_server_list_str"; then config_success=0; fi ;;   # Call configure_ntpd with type ntpd
        unknown) log_error "无法检测/配置任何已知时间同步服务"; exit 1 ;;
    esac

    if [ $config_success -ne 0 ]; then log_error "配置 $time_service 服务失败"; exit 1; fi
    if ! verify_time_sync "$time_service"; then log_warning "最终时间同步验证未完全成功"; fi

    log "====== 时间同步配置完成 ======"
    log_success "最终系统时间: $(date)"
    log "配置的服务: $time_service"
    log "使用的NTP服务器: $ntp_server_list_str"
    log "当前时区: $(date +%Z) ($(timedatectl status | grep 'Time zone:' | awk '{print $3}'))"
}

# 运行主函数
main
