#!/bin/bash
set -euo pipefail

echo "=== 通用 Linux 初始化脚本（阿里云版） ==="

# 获取系统信息
DISTRO_ID=$(grep ^ID= /etc/os-release | cut -d= -f2 | tr -d '"')
DISTRO_NAME=$(grep ^PRETTY_NAME= /etc/os-release | cut -d= -f2 | tr -d '"')
CODENAME=$(lsb_release -cs 2>/dev/null || echo "")

echo "检测到系统: $DISTRO_NAME"

# 设置 DNS
set_dns() {
    echo "配置 DNS 到 114.114.114.114 和 223.5.5.5..."
    echo -e "nameserver 114.114.114.114\nnameserver 223.5.5.5" > /etc/resolv.conf || true
}

# 设置时区和同步时间
set_timezone() {
    echo "设置时区为 Asia/Shanghai..."
    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime || true
    if command -v timedatectl >/dev/null 2>&1; then
        timedatectl set-timezone Asia/Shanghai || true
        timedatectl set-ntp true || true
    else
        echo "timedatectl 不可用，尝试使用 ntpdate..."
        (apt install -y ntpdate || yum install -y ntpdate || dnf install -y ntpdate) >/dev/null 2>&1 || true
        ntpdate ntp.aliyun.com || true
    fi
}

# 设置软件源
set_mirrors() {
    echo "更换软件源为阿里云镜像..."

    case "$DISTRO_ID" in
        ubuntu)
            cat > /etc/apt/sources.list <<EOF
deb http://mirrors.aliyun.com/ubuntu/ ${CODENAME} main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ ${CODENAME}-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ ${CODENAME}-backports main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ ${CODENAME}-security main restricted universe multiverse
EOF
            apt update -y || true
            ;;

        debian|raspbian)
            cat > /etc/apt/sources.list <<EOF
deb http://mirrors.aliyun.com/${DISTRO_ID}/ ${CODENAME} main contrib non-free non-free-firmware
deb http://mirrors.aliyun.com/${DISTRO_ID}/ ${CODENAME}-updates main contrib non-free non-free-firmware
deb http://mirrors.aliyun.com/${DISTRO_ID}/ ${CODENAME}-backports main contrib non-free non-free-firmware
deb http://mirrors.aliyun.com/${DISTRO_ID}-security ${CODENAME}-security main contrib non-free non-free-firmware
EOF
            apt update -y || true
            ;;

        centos|rhel|almalinux|rocky)
            echo "配置 RHEL 系列阿里云镜像..."
            if [ -f /etc/yum.repos.d/CentOS-Base.repo ]; then
                sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' \
                           -e 's|^#baseurl=http://mirror.centos.org|baseurl=http://mirrors.aliyun.com|g' \
                           /etc/yum.repos.d/CentOS-Base.repo
            fi
            yum makecache || true
            ;;

        fedora)
            echo "配置 Fedora 阿里云镜像..."
            sed -i.bak -e 's|^metalink=|#metalink=|g' \
                       -e 's|^#baseurl=https://download.example/pub|baseurl=http://mirrors.aliyun.com/fedora|g' \
                       /etc/yum.repos.d/fedora*.repo
            dnf makecache || true
            ;;

        *)
            echo "不支持的系统类型：$DISTRO_ID，跳过换源"
            ;;
    esac
}

# 主执行函数
main() {
    set_mirrors
    set_dns
    set_timezone
    echo "✅ 初始化完成。"
}

main
