#!/bin/bash
# Debian 12 系统优化脚本（优化版）
# 功能：配置SSH服务、系统时区、内核参数、Docker路径等

# 检查是否以root用户运行
if [ "$(id -u)" -ne 0 ]; then
    echo "错误：此脚本需要以root权限运行。请使用sudo或切换到root用户。" >&2
    exit 1
fi

# 配置SSH服务
configure_ssh() {
    echo "开始配置SSH服务..."
    
    # 备份原始SSH配置
    cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%Y%m%d%H%M%S)
    
    # 允许root远程登录
    sed -i 's/^#*PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config
    
    # 允许密码登录
    sed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication yes/' /etc/ssh/sshd_config
    
    # 允许密钥登录
    sed -i 's/^#*PubkeyAuthentication.*/PubkeyAuthentication yes/' /etc/ssh/sshd_config
    
    # 优化SSH连接速度
    echo "
# 优化SSH连接速度
UseDNS no
GSSAPIAuthentication no
ClientAliveInterval 60
ClientAliveCountMax 10
Compression yes
TCPKeepAlive yes
MaxStartups 100
LoginGraceTime 30
" >> /etc/ssh/sshd_config
    
    # 重启SSH服务使配置生效
    systemctl restart sshd
    
    echo "SSH服务配置完成。"
}

# 设置系统时区为上海时间
configure_timezone() {
    echo "开始设置系统时区为上海时间..."
    
    # 设置时区为上海
    timedatectl set-timezone Asia/Shanghai
    
    # 启用NTP同步
    timedatectl set-ntp yes
    
    # 安装并配置chrony以获得更精确的时间同步
    apt update && apt install -y chrony
    sed -i 's/^pool.*/pool ntp.aliyun.com iburst/' /etc/chrony/chrony.conf
    systemctl restart chronyd
    chronyc sources
    
    echo "系统时区设置完成。当前时间：$(date)"
}

# 优化系统内核参数
optimize_kernel() {
    echo "开始优化系统内核参数..."
    
    # 备份原始sysctl配置
    cp /etc/sysctl.conf /etc/sysctl.conf.bak.$(date +%Y%m%d%H%M%S)
    
    # 添加内核优化参数
    cat << EOF >> /etc/sysctl.conf

# 系统内核优化参数 - 网络优化
net.core.netdev_max_backlog = 16384
net.core.somaxconn = 8192
net.core.rmem_default = 262144
net.core.wmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_synack_retries = 3
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_keepalive_time = 1800
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl = 15
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_no_metrics_save = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_congestion_control = cubic
net.ipv4.tcp_fastopen = 3

# 文件系统优化
fs.file-max = 1000000
fs.inotify.max_user_instances = 8192
fs.inotify.max_user_watches = 1048576

# 虚拟内存优化
vm.swappiness = 5
vm.vfs_cache_pressure = 50
vm.overcommit_memory = 1
vm.dirty_ratio = 10
vm.dirty_background_ratio = 5

# 现代内核调度优化
kernel.sched_autogroup_enabled = 0
EOF
    
    # 使内核参数生效
    sysctl -p
    
    echo "系统内核参数优化完成。"
}

# 优化文件打开数限制
optimize_file_limits() {
    echo "开始优化文件打开数限制..."
    
    # 备份原始limits配置
    cp /etc/security/limits.conf /etc/security/limits.conf.bak.$(date +%Y%m%d%H%M%S)
    
    # 设置文件打开数限制
    cat << EOF >> /etc/security/limits.conf

# 提高文件打开数限制
* soft nofile 65536
* hard nofile 1048576
root soft nofile 65536
root hard nofile 1048576
* soft nproc 65536
* hard nproc 1048576
root soft nproc 65536
root hard nproc 1048576
EOF
    
    # 对于systemd管理的服务，需要额外配置
    mkdir -p /etc/systemd/system.conf.d/
    cat << EOF > /etc/systemd/system.conf.d/limits.conf
[Manager]
DefaultLimitNOFILE=1048576
DefaultLimitNPROC=1048576
EOF
    
    systemctl daemon-reload
    
    echo "文件打开数限制优化完成。"
}

# 更换Docker默认存储路径到home目录
configure_docker_path() {
    echo "开始配置Docker默认存储路径..."
    
    # 检查Docker是否已安装
    if ! command -v docker &> /dev/null; then
        echo "Docker未安装，将先安装Docker..."
        # 安装Docker
        apt update && apt install -y docker.io docker-compose
        systemctl enable --now docker
    fi
    
    # 定义新的Docker存储路径
    NEW_DOCKER_PATH="/home/docker"
    
    # 停止Docker服务
    systemctl stop docker
    systemctl stop docker.socket
    
    # 备份当前Docker数据
    if [ -d "/var/lib/docker" ] && [ "$(ls -A /var/lib/docker)" ]; then
        echo "备份当前Docker数据..."
        cp -rp /var/lib/docker /var/lib/docker.bak.$(date +%Y%m%d%H%M%S)
    fi
    
    # 创建新目录并设置权限
    mkdir -p $NEW_DOCKER_PATH
    chown -R root:root $NEW_DOCKER_PATH
    chmod -R 711 $NEW_DOCKER_PATH
    
    # 迁移现有Docker数据到新路径
    if [ -d "/var/lib/docker" ] && [ "$(ls -A /var/lib/docker)" ]; then
        echo "迁移Docker数据到新路径..."
        rsync -avz /var/lib/docker/ $NEW_DOCKER_PATH/
    fi
    
    # 配置Docker使用新路径
    mkdir -p /etc/docker
    if [ -f "/etc/docker/daemon.json" ]; then
        # 备份现有配置
        cp /etc/docker/daemon.json /etc/docker/daemon.json.bak.$(date +%Y%m%d%H%M%S)
        
        # 检查是否已有data-root配置
        if grep -q "data-root" /etc/docker/daemon.json; then
            # 修改现有配置
            sed -i "s|\"data-root\": \".*\"|\"data-root\": \"$NEW_DOCKER_PATH\"|g" /etc/docker/daemon.json
        else
            # 添加新配置（处理JSON格式）
            sed -i '$ s/}$/, "data-root": "'"$NEW_DOCKER_PATH"'"}/' /etc/docker/daemon.json
        fi
    else
        # 创建新的配置文件
        cat << EOF > /etc/docker/daemon.json
{
    "data-root": "$NEW_DOCKER_PATH"
}
EOF
    fi
    
    # 重启Docker服务
    systemctl daemon-reload
    systemctl start docker
    
    # 验证配置是否生效
    if docker info | grep -q "Docker Root Dir: $NEW_DOCKER_PATH"; then
        echo "Docker默认存储路径已成功更改为: $NEW_DOCKER_PATH"
        
        # 可选：删除原始Docker目录（确认迁移成功后）
        # rm -rf /var/lib/docker
    else
        echo "警告：Docker路径更改可能未生效，请检查配置。"
    fi
}

# 其他系统性能优化
additional_optimizations() {
    echo "开始其他系统性能优化..."
    
    # 安装必要的系统工具
    apt install -y htop sudo iotop iftop net-tools sysstat ncdu wget curl ftp btop
    
    # 启用sysstat监控系统性能
    sed -i 's/^ENABLED=.*/ENABLED="true"/' /etc/default/sysstat
    systemctl restart sysstat
    
    # 优化Bash环境
    echo "
# 历史命令时间戳
HISTTIMEFORMAT=\"%F %T \"
# 增加历史命令记录数量
HISTSIZE=100000
HISTFILESIZE=1000000
" >> /etc/bash.bashrc
    
    # 禁用IPv6（如果不需要）
    echo "net.ipv6.conf.all.disable_ipv6 = 1" >> /etc/sysctl.conf
    echo "net.ipv6.conf.default.disable_ipv6 = 1" >> /etc/sysctl.conf
    sysctl -p
    
    echo "其他系统性能优化完成。"
}

# 主函数
main() {
    echo "===== 开始Debian 12系统优化 ====="
    
    configure_ssh
    configure_timezone
    optimize_kernel
    optimize_file_limits
    configure_docker_path
    additional_optimizations
    
    echo "===== 系统优化完成 ====="
    echo "建议执行 'reboot' 重启系统以确保所有配置生效。"
}

# 执行主函数
main

