#!/bin/bash
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
plain='\033[0m'

echo -e "${green}===== 同步系统时间(中国时区 Asia/Shanghai) =====${plain}"

# 检测系统
if [[ -f /etc/redhat-release ]]; then
    release="centos"
elif grep -Eqi "debian" /etc/issue 2>/dev/null; then
    release="debian"
elif grep -Eqi "ubuntu" /etc/issue 2>/dev/null; then
    release="ubuntu"
elif grep -Eqi "centos|red hat|redhat" /etc/issue 2>/dev/null; then
    release="centos"
elif grep -Eqi "alpine" /etc/os-release 2>/dev/null; then
    release="alpine"
elif grep -Eqi "arch" /etc/os-release 2>/dev/null; then
    release="arch"
else
    release="unknown"
fi
echo -e "${green}检测系统: ${release}${plain}"

# 1. 设置时区
echo -e "${green}[1/4] 设置时区 Asia/Shanghai...${plain}"
if command -v timedatectl &> /dev/null; then
    timedatectl set-timezone Asia/Shanghai
    timedatectl set-ntp false 2>/dev/null
else
    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
    echo "Asia/Shanghai" > /etc/timezone 2>/dev/null || true
fi

# 2. 先检测NTP端口是否可用(快速探测,2秒超时)
echo -e "${green}[2/4] 检测NTP端口...${plain}"
ntp_available=false
if command -v nc &> /dev/null; then
    if nc -zu -w2 ntp.aliyun.com 123 2>/dev/null; then
        ntp_available=true
    fi
elif command -v timeout &> /dev/null; then
    if timeout 2 bash -c 'echo >/dev/udp/ntp.aliyun.com/123' 2>/dev/null; then
        ntp_available=true
    fi
fi

if [ "$ntp_available" = true ]; then
    echo -e "${green}  NTP端口(UDP 123)可用${plain}"
else
    echo -e "${yellow}  NTP端口(UDP 123)不可用或被防火墙拦截，将直接使用HTTP同步${plain}"
fi

# 停掉可能占用端口的服务
systemctl stop chronyd 2>/dev/null
systemctl stop ntpd 2>/dev/null
systemctl stop ntp 2>/dev/null

# 3. 同步时间
echo -e "${green}[3/4] 同步时间...${plain}"
sync_ok=false
NTP_SERVERS="ntp.aliyun.com ntp.tencent.com cn.ntp.org.cn pool.ntp.org"

# ========== 方式1: NTP同步(仅在端口可用时尝试) ==========
if [ "$ntp_available" = true ]; then

    # 1a: 经典ntpdate(非ntpsec版本)
    NTPDATE_BIN=""
    if command -v ntpdate &> /dev/null; then
        # 检测是不是真正的ntpdate还是ntpsec的wrapper
        if ntpdate --version 2>&1 | grep -qi "ntpsec\|ntpdig"; then
            NTPDATE_BIN=""  # ntpsec版本,语法不同,跳过
        else
            NTPDATE_BIN="ntpdate"
        fi
    fi

    if [ -n "$NTPDATE_BIN" ]; then
        for server in $NTP_SERVERS; do
            echo -e "  尝试 ntpdate ${server}..."
            if timeout 5 ntpdate -u "$server" 2>&1; then
                echo -e "${green}  同步成功 via ntpdate (${server})${plain}"
                sync_ok=true
                break
            fi
        done
    fi

    # 1b: ntpdig(ntpsec版本)
    if [ "$sync_ok" = false ] && command -v ntpdig &> /dev/null; then
        for server in $NTP_SERVERS; do
            echo -e "  尝试 ntpdig ${server}..."
            result=$(timeout 5 ntpdig -S "$server" 2>/dev/null)
            if [ $? -eq 0 ] && [ -n "$result" ]; then
                echo -e "${green}  同步成功 via ntpdig (${server})${plain}"
                sync_ok=true
                break
            fi
        done
    fi

    # 1c: chronyd -q 单次同步
    if [ "$sync_ok" = false ] && command -v chronyd &> /dev/null; then
        for server in ntp.aliyun.com pool.ntp.org; do
            echo -e "  尝试 chronyd ${server}..."
            if timeout 8 chronyd -q "server ${server} iburst" 2>&1 | grep -q "System clock.*adjusted"; then
                echo -e "${green}  同步成功 via chronyd (${server})${plain}"
                sync_ok=true
                break
            fi
        done
    fi
fi

# ========== 方式2: HTTP同步(通过HTTP头获取时间) ==========
if [ "$sync_ok" = false ]; then
    echo -e "${yellow}  使用HTTP同步时间...${plain}"
    HTTP_SITES="http://www.baidu.com http://www.taobao.com http://www.qq.com http://www.163.com"
    for site in $HTTP_SITES; do
        net_time=$(curl -sI --connect-timeout 3 --max-time 5 "$site" 2>/dev/null | grep -i '^Date:' | sed 's/^[Dd]ate: //')
        if [ -n "$net_time" ]; then
            echo -e "  获取到时间: ${net_time}"
            if date -s "$net_time" 2>/dev/null; then
                echo -e "${green}  同步成功 via HTTP (${site})${plain}"
                sync_ok=true
                break
            fi
        fi
    done
fi

# ========== 方式3: HTTPS API ==========
if [ "$sync_ok" = false ]; then
    echo -e "${yellow}  尝试HTTPS API获取时间...${plain}"
    api_time=$(curl -s --connect-timeout 3 --max-time 5 "http://worldtimeapi.org/api/timezone/Asia/Shanghai" 2>/dev/null | grep -o '"datetime":"[^"]*"' | cut -d'"' -f4 | head -1)
    if [ -n "$api_time" ]; then
        if date -s "$api_time" 2>/dev/null; then
            echo -e "${green}  同步成功 via API${plain}"
            sync_ok=true
        fi
    fi
fi

# 设置chrony长期保持(后台)
if command -v chronyd &> /dev/null; then
    cat > /etc/chrony.conf 2>/dev/null << 'EOF'
server ntp.aliyun.com iburst
server ntp.tencent.com iburst
server cn.ntp.org.cn iburst
server pool.ntp.org iburst
driftfile /var/lib/chrony/drift
makestep 1.0 3
rtcsync
logdir /var/log/chrony
EOF
    systemctl restart chronyd 2>/dev/null && systemctl enable chronyd 2>/dev/null
fi

# 4. 同步硬件时钟
echo -e "${green}[4/4] 同步硬件时钟...${plain}"
if command -v hwclock &> /dev/null; then
    hwclock -w 2>/dev/null && echo -e "${green}  硬件时钟已同步${plain}"
fi

# 结果
echo ""
echo -e "${green}===== 同步完成 =====${plain}"
echo -e "${green}当前时间: $(date '+%Y-%m-%d %H:%M:%S %Z')${plain}"
if [ "$sync_ok" = true ]; then
    echo -e "${green}同步状态: 成功${plain}"
else
    echo -e "${red}同步状态: 失败，请检查网络${plain}"
fi
