cat > /root/init_time_update_bbr.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

log(){ echo -e "\033[1;32m==>\033[0m $*"; }
warn(){ echo -e "\033[1;33m[WARN]\033[0m $*"; }
err(){ echo -e "\033[1;31m[ERR]\033[0m $*" >&2; }

[[ $EUID -ne 0 ]] && err "请用 root 运行（sudo -i）。" && exit 1

# ---- 识别发行版/架构 ----
release=""
if [[ -f /etc/os-release ]]; then . /etc/os-release; fi
case "${ID:-}" in
  ubuntu) release="ubuntu" ;;
  debian) release="debian" ;;
  centos|rhel|rocky|almalinux) release="centos" ;;
esac
if [[ -z "$release" ]]; then
  if grep -Eqi "debian" /etc/issue /proc/version 2>/dev/null; then release="debian"
  elif grep -Eqi "ubuntu" /etc/issue /proc/version 2>/dev/null; then release="ubuntu"
  elif grep -Eqi "centos|red hat|redhat" /etc/issue /proc/version 2>/dev/null; then release="centos"
  else err "未识别的系统"; exit 1; fi
fi

arch_raw=$(uname -m)
if [[ "$arch_raw" =~ (x86_64|amd64|x64) ]]; then arch_sp="64"
elif [[ "$arch_raw" =~ (aarch64|arm64) ]]; then arch_sp="arm64-v8a"
else arch_sp="64"; warn "未知架构 $arch_raw，按 x86_64 处理"; fi

# ---- 1) 先：设置北京时间 + 时间同步（chrony 优先 AWS 源）----
sync_time() {
  local TZ_NAME="Asia/Shanghai"
  log "设置时区为 ${TZ_NAME} ..."
  if command -v timedatectl >/dev/null 2>&1; then
    timedatectl set-timezone "${TZ_NAME}" || true
  else
    ln -sf "/usr/share/zoneinfo/${TZ_NAME}" /etc/localtime
    echo "${TZ_NAME}" >/etc/timezone || true
  fi

  log "安装/配置 chrony ..."
  if [[ "$release" == "centos" ]]; then
    yum -y install chrony >/dev/null 2>&1 || yum -y install chrony
  else
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -y
    apt-get install -y chrony
    systemctl disable --now systemd-timesyncd 2>/dev/null || true
  fi

  local CHRONY_CONF="/etc/chrony/chrony.conf"
  [[ -f /etc/chrony.conf ]] && CHRONY_CONF="/etc/chrony.conf"

  grep -qE '^\s*sourcedir\s+/etc/chrony/sources\.d' "$CHRONY_CONF" || echo 'sourcedir /etc/chrony/sources.d' >> "$CHRONY_CONF"
  mkdir -p /etc/chrony/sources.d
  cat >/etc/chrony/sources.d/aws-timesync.sources <<'EOC'
# AWS EC2 本地时间服务（在非 EC2 上不可达也无碍）
server 169.254.169.123 prefer iburst minpoll 4 maxpoll 6
# 公网回退
pool pool.ntp.org iburst
EOC

  systemctl enable --now chrony
  chronyc -a makestep || true
  sleep 1
  log "时间同步完成："
  timedatectl || true
  chronyc tracking || true
}
sync_time

# ---- 2) 然后：系统更新 & 升级（update/upgrade）----
log "开始系统更新 ..."
if [[ "$release" == "centos" ]]; then
  yum -y update || true
else
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -y
  # 使用 full-upgrade，自动处理依赖/内核升级
  apt-get -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold full-upgrade -y || true
  apt-get autoremove -y || true
  apt-get autoclean -y || true
fi

# ---- 3) BBR：开启并校验（现代安全配置，精简且有效）----
enable_bbr() {
  log "加载 tcp_bbr 模块（如有） ..."
  modprobe tcp_bbr 2>/dev/null || true

  # 写入 drop-in，而不是覆盖 /etc/sysctl.conf（更安全）
  mkdir -p /etc/sysctl.d

  # ★★ BBR 最优实践（精简）：仅设置必要项 + 一些安全加速项 ★★
  cat >/etc/sysctl.d/99-bbr-optimal.conf <<'SYS'
# --- BBR 基础 ---
net.core.default_qdisc=fq
net.ipv4.tcp_congestion_control=bbr

# --- 安全的缓冲与队列（适中值，避免过度）---
net.core.rmem_max=134217728
net.core.wmem_max=134217728
net.ipv4.tcp_rmem=4096 87380 134217728
net.ipv4.tcp_wmem=4096 65536 134217728
net.core.netdev_max_backlog=250000

# --- 网络「黑洞」探测，避免某些链路丢包导致的卡死 ---
net.ipv4.tcp_mtu_probing=1

# --- 其它常见安全项 ---
net.ipv4.tcp_syncookies=1
net.ipv4.ip_forward=1
SYS

  sysctl --system >/dev/null || sysctl -p /etc/sysctl.d/99-bbr-optimal.conf >/dev/null

  log "验证 BBR 是否生效："
  sysctl net.ipv4.tcp_congestion_control
  sysctl net.core.default_qdisc
  if lsmod 2>/dev/null | grep -q bbr; then
    echo "lsmod: $(lsmod | grep bbr | tr -s ' ' | cut -d' ' -f1-3)"
  else
    echo "lsmod: 未看到 tcp_bbr 模块（有的发行版编进内核，不显示也正常）"
  fi

  # 提示 reboot 情况（若内核升级了）
  if [[ -f /var/run/reboot-required ]]; then
    warn "系统提示需要重启以加载新内核/库（/var/run/reboot-required 存在）。"
  fi
}
enable_bbr

# ---- 4) 你的其余任务（保留/可选）----
# 这里仅演示：speedtest 安装（如需要）
if ! command -v speedtest >/dev/null 2>&1; then
  log "安装 speedtest ..."
  wget -q "https://file.myluckys.org/file/speedtest-${arch_sp}" -O /usr/bin/speedtest && chmod +x /usr/bin/speedtest || warn "speedtest 下载失败"
fi

log "全部完成 ✅ 当前时间：$(date '+%F %T %Z')"
EOF

chmod +x /root/init_time_update_bbr.sh
bash /root/init_time_update_bbr.sh
