#!/bin/bash

set -e

echo "=== CentOS 7 时间同步脚本开始 ==="

# 1. 检查是否 root
if [ "$(id -u)" -ne 0 ]; then
    echo "请使用 root 用户执行"
    exit 1
fi

# 2. 设置时区
echo "[1/6] 设置时区为 Asia/Shanghai"
timedatectl set-timezone Asia/Shanghai

# 3. 安装 chrony
echo "[2/6] 安装 chrony"
if ! rpm -q chrony &>/dev/null; then
    yum install -y chrony
else
    echo "chrony 已安装，跳过"
fi

# 4. 配置 NTP 服务器
echo "[3/6] 配置 NTP 服务器"
CONF="/etc/chrony.conf"

sed -i 's/^server /#server /g' "$CONF"

grep -q "ntp.aliyun.com" "$CONF" || cat >> "$CONF" <<EOF

# China NTP servers
server ntp.aliyun.com iburst
server ntp.tencent.com iburst
server ntp1.aliyun.com iburst
EOF

# 5. 启动并启用 chronyd
echo "[4/6] 启动 chronyd"
systemctl enable chronyd --now

# 6. 立即强制同步
echo "[5/6] 强制同步系统时间"
chronyc -a makestep

# 7. 写入硬件时间
echo "[6/6] 写入硬件时钟"
hwclock --systohc

echo "=== 时间同步完成 ==="
echo
timedatectl status
