#!/bin/bash

#==============================================================================
# 脚本名称: optimize_system.sh
# 描述: VPS系统优化脚本 - 优化系统性能、内核参数、网络设置等
# 作者: Jensfrank
# 路径: vps_scripts/scripts/system_tools/optimize_system.sh
# 使用方法: bash optimize_system.sh [选项]
# 选项: --auto (自动优化) --network (仅网络) --kernel (仅内核) --security (安全加固)
# 更新日期: 2024-06-17
#==============================================================================

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[0;37m'
NC='\033[0m' # No Color

# 配置变量
LOG_DIR="/var/log/vps_scripts"
LOG_FILE="$LOG_DIR/optimize_system_$(date +%Y%m%d_%H%M%S).log"
BACKUP_DIR="/var/backups/system_optimize"
CONFIG_BACKUP_DIR="$BACKUP_DIR/configs_$(date +%Y%m%d_%H%M%S)"

# 运行模式
AUTO_MODE=false
OPTIMIZE_NETWORK=true
OPTIMIZE_KERNEL=true
OPTIMIZE_SECURITY=true
OPTIMIZE_SERVICES=true
OPTIMIZE_FILESYSTEM=true

# 系统信息
OS_TYPE=""
OS_VERSION=""
TOTAL_RAM=0
CPU_CORES=0
IS_VIRTUAL=false

# 创建必要目录
create_directories() {
    [ ! -d "$LOG_DIR" ] && mkdir -p "$LOG_DIR"
    [ ! -d "$BACKUP_DIR" ] && mkdir -p "$BACKUP_DIR"
    [ ! -d "$CONFIG_BACKUP_DIR" ] && mkdir -p "$CONFIG_BACKUP_DIR"
}

# 检查root权限
check_root() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}错误: 此脚本需要root权限运行${NC}"
        echo -e "${YELLOW}请使用 sudo bash $0 或切换到root用户${NC}"
        exit 1
    fi
}

# 日志记录函数
log() {
    local level=$1
    shift
    local message="$@"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $message" >> "$LOG_FILE"
}

# 打印带颜色的消息
print_msg() {
    local color=$1
    local msg=$2
    echo -e "${color}${msg}${NC}"
    log "INFO" "$msg"
}

# 打印进度
print_progress() {
    local msg=$1
    echo -ne "\r${CYAN}[处理中]${NC} $msg..."
}

# 检测系统信息
detect_system() {
    print_msg "$BLUE" "检测系统信息..."
    
    # 检测操作系统
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS_TYPE=$ID
        OS_VERSION=$VERSION_ID
    else
        print_msg "$RED" "无法识别的操作系统"
        exit 1
    fi
    
    # 获取内存大小（MB）
    TOTAL_RAM=$(free -m | awk 'NR==2{print $2}')
    
    # 获取CPU核心数
    CPU_CORES=$(nproc)
    
    # 检测是否为虚拟机
    if systemd-detect-virt &> /dev/null; then
        IS_VIRTUAL=true
        VIRT_TYPE=$(systemd-detect-virt)
    fi
    
    print_msg "$GREEN" "系统: $OS_TYPE $OS_VERSION"
    print_msg "$GREEN" "内存: ${TOTAL_RAM}MB | CPU核心: ${CPU_CORES}"
    [ "$IS_VIRTUAL" = true ] && print_msg "$GREEN" "虚拟化: $VIRT_TYPE"
}

# 备份配置文件
backup_configs() {
    print_msg "$BLUE" "备份系统配置..."
    
    local configs=(
        "/etc/sysctl.conf"
        "/etc/sysctl.d/"
        "/etc/security/limits.conf"
        "/etc/systemd/system.conf"
        "/etc/systemd/user.conf"
        "/etc/fstab"
        "/etc/default/grub"
        "/etc/ssh/sshd_config"
    )
    
    for config in "${configs[@]}"; do
        if [ -e "$config" ]; then
            cp -a "$config" "$CONFIG_BACKUP_DIR/" 2>/dev/null
        fi
    done
    
    print_msg "$GREEN" "配置备份完成: $CONFIG_BACKUP_DIR"
}

# 优化内核参数
optimize_kernel_parameters() {
    if [ "$OPTIMIZE_KERNEL" = false ]; then
        return
    fi
    
    print_msg "$BLUE" "\n优化内核参数..."
    
    # 创建自定义sysctl配置文件
    cat > /etc/sysctl.d/99-vps-optimize.conf << EOF
# VPS System Optimization - Generated by optimize_system.sh
# $(date '+%Y-%m-%d %H:%M:%S')

# 网络优化
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 0
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.tcp_fastopen = 3
net.ipv4.tcp_rmem = 4096 87380 67108864
net.ipv4.tcp_wmem = 4096 65536 67108864
net.ipv4.tcp_mtu_probing = 1

# 如果是高内存系统（>2GB），启用更激进的设置
$([ $TOTAL_RAM -gt 2048 ] && echo "net.ipv4.tcp_mem = 65536 131072 262144")
$([ $TOTAL_RAM -gt 2048 ] && echo "net.ipv4.udp_mem = 65536 131072 262144")

# 网络安全
net.ipv4.tcp_rfc1337 = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1

# 内存管理
vm.swappiness = 10
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5
vm.overcommit_memory = 1
vm.min_free_kbytes = $((TOTAL_RAM * 1024 * 5 / 100))  # 5% of total RAM

# 文件系统
fs.file-max = 65535
fs.inotify.max_user_watches = 524288

# 内核
kernel.pid_max = 65536
kernel.threads-max = 65536
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = $(($TOTAL_RAM * 1024 * 1024))
kernel.shmall = $(($TOTAL_RAM * 256))

# BBR拥塞控制（如果内核支持）
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr

# 网络缓冲区
net.core.rmem_default = 262144
net.core.wmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 5000
net.core.somaxconn = 4096

# IPv6设置（如果需要可以禁用）
# net.ipv6.conf.all.disable_ipv6 = 1
# net.ipv6.conf.default.disable_ipv6 = 1
EOF

    # 应用设置
    sysctl -p /etc/sysctl.d/99-vps-optimize.conf &>> "$LOG_FILE"
    
    print_msg "$GREEN" "内核参数优化完成"
}

# 优化网络设置
optimize_network() {
    if [ "$OPTIMIZE_NETWORK" = false ]; then
        return
    fi
    
    print_msg "$BLUE" "\n优化网络设置..."
    
    # 启用BBR（如果可用）
    if modprobe tcp_bbr &> /dev/null; then
        echo "tcp_bbr" >> /etc/modules-load.d/modules.conf
        print_msg "$GREEN" "BBR拥塞控制已启用"
    else
        print_msg "$YELLOW" "BBR不可用，使用默认拥塞控制"
    fi
    
    # 优化网络接口设置
    for interface in $(ls /sys/class/net/ | grep -v lo); do
        if [ -d "/sys/class/net/$interface" ]; then
            # 启用网卡多队列（如果支持）
            if [ -f "/sys/class/net/$interface/queues/rx-0/rps_cpus" ]; then
                echo f > /sys/class/net/$interface/queues/rx-0/rps_cpus 2>/dev/null
            fi
            
            # 增加网卡缓冲区（如果支持）
            ethtool -G $interface rx 4096 tx 4096 &> /dev/null
        fi
    done
    
    # 禁用不必要的网络协议
    cat > /etc/modprobe.d/blacklist-rare-network.conf << EOF
# Disable rare network protocols
blacklist dccp
blacklist sctp
blacklist rds
blacklist tipc
EOF
    
    print_msg "$GREEN" "网络优化完成"
}

# 优化系统限制
optimize_limits() {
    print_msg "$BLUE" "\n优化系统限制..."
    
    # 备份原文件
    cp /etc/security/limits.conf /etc/security/limits.conf.bak
    
    # 添加优化设置
    cat >> /etc/security/limits.conf << EOF

# VPS Optimization - Added by optimize_system.sh
* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535
* soft memlock unlimited
* hard memlock unlimited
EOF
    
    # 为systemd设置限制
    mkdir -p /etc/systemd/system.conf.d/
    cat > /etc/systemd/system.conf.d/99-limits.conf << EOF
[Manager]
DefaultLimitNOFILE=65535
DefaultLimitNPROC=65535
DefaultTasksMax=65535
EOF
    
    # 重载systemd配置
    systemctl daemon-reload
    
    print_msg "$GREEN" "系统限制优化完成"
}

# 优化文件系统
optimize_filesystem() {
    if [ "$OPTIMIZE_FILESYSTEM" = false ]; then
        return
    fi
    
    print_msg "$BLUE" "\n优化文件系统..."
    
    # 获取根分区文件系统类型
    ROOT_FS=$(df -T / | awk 'NR==2 {print $2}')
    
    case $ROOT_FS in
        ext4)
            # 优化ext4挂载选项
            if grep -q " / " /etc/fstab; then
                # 添加noatime选项以减少磁盘写入
                sed -i '/ \/ /s/defaults/defaults,noatime,nodiratime/' /etc/fstab
                print_msg "$GREEN" "EXT4文件系统优化完成"
            fi
            ;;
        xfs)
            # XFS优化
            if grep -q " / " /etc/fstab; then
                sed -i '/ \/ /s/defaults/defaults,noatime,nodiratime/' /etc/fstab
                print_msg "$GREEN" "XFS文件系统优化完成"
            fi
            ;;
        btrfs)
            # Btrfs优化
            if grep -q " / " /etc/fstab; then
                sed -i '/ \/ /s/defaults/defaults,noatime,compress=zstd,space_cache=v2/' /etc/fstab
                print_msg "$GREEN" "Btrfs文件系统优化完成"
            fi
            ;;
    esac
    
    # 调整预读设置
    for device in $(lsblk -d -n -o NAME | grep -E '^(sd|vd|nvme)'); do
        echo 256 > /sys/block/$device/queue/read_ahead_kb 2>/dev/null
    done
    
    # 优化I/O调度器
    for device in $(lsblk -d -n -o NAME | grep -E '^(sd|vd|nvme)'); do
        if [ "$IS_VIRTUAL" = true ]; then
            # 虚拟机使用none/noop调度器
            echo noop > /sys/block/$device/queue/scheduler 2>/dev/null || \
            echo none > /sys/block/$device/queue/scheduler 2>/dev/null
        else
            # 物理机使用deadline调度器
            echo deadline > /sys/block/$device/queue/scheduler 2>/dev/null || \
            echo mq-deadline > /sys/block/$device/queue/scheduler 2>/dev/null
        fi
    done
    
    print_msg "$GREEN" "文件系统优化完成"
}

# 优化内存和Swap
optimize_memory() {
    print_msg "$BLUE" "\n优化内存管理..."
    
    # 检查并创建swap（如果需要）
    SWAP_SIZE=$(free -m | awk '/^Swap:/ {print $2}')
    
    if [ "$SWAP_SIZE" -eq 0 ]; then
        print_msg "$YELLOW" "未检测到Swap分区"
        
        if [ "$AUTO_MODE" = true ] || { read -p "是否创建Swap文件？(y/N): " confirm && [[ "$confirm" =~ ^[Yy]$ ]]; }; then
            # 根据内存大小决定swap大小
            if [ $TOTAL_RAM -le 2048 ]; then
                SWAP_MB=$((TOTAL_RAM * 2))
            else
                SWAP_MB=$TOTAL_RAM
            fi
            
            # 创建swap文件
            print_progress "创建${SWAP_MB}MB的Swap文件"
            dd if=/dev/zero of=/swapfile bs=1M count=$SWAP_MB status=progress &>> "$LOG_FILE"
            chmod 600 /swapfile
            mkswap /swapfile &>> "$LOG_FILE"
            swapon /swapfile &>> "$LOG_FILE"
            
            # 添加到fstab
            if ! grep -q "/swapfile" /etc/fstab; then
                echo "/swapfile none swap sw 0 0" >> /etc/fstab
            fi
            
            echo -e "\r${GREEN}[完成]${NC} Swap文件创建成功（${SWAP_MB}MB）"
        fi
    fi
    
    # 启用zram压缩内存（如果可用）
    if modprobe zram &> /dev/null && [ $TOTAL_RAM -le 4096 ]; then
        print_msg "$CYAN" "配置ZRAM压缩内存..."
        
        cat > /etc/systemd/system/zram.service << EOF
[Unit]
Description=Configure zram swap device
After=multi-user.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/bin/zram-config.sh start
ExecStop=/usr/local/bin/zram-config.sh stop

[Install]
WantedBy=multi-user.target
EOF

        cat > /usr/local/bin/zram-config.sh << 'EOF'
#!/bin/bash
case $1 in
  start)
    modprobe zram
    echo lz4 > /sys/block/zram0/comp_algorithm
    echo $(($(free -m | awk '/^Mem:/{print $2}') / 2))M > /sys/block/zram0/disksize
    mkswap /dev/zram0
    swapon -p 10 /dev/zram0
    ;;
  stop)
    swapoff /dev/zram0
    echo 1 > /sys/block/zram0/reset
    modprobe -r zram
    ;;
esac
EOF
        
        chmod +x /usr/local/bin/zram-config.sh
        systemctl enable zram.service &>> "$LOG_FILE"
        systemctl start zram.service &>> "$LOG_FILE"
        
        print_msg "$GREEN" "ZRAM压缩内存已启用"
    fi
    
    print_msg "$GREEN" "内存优化完成"
}

# 优化系统服务
optimize_services() {
    if [ "$OPTIMIZE_SERVICES" = false ]; then
        return
    fi
    
    print_msg "$BLUE" "\n优化系统服务..."
    
    # 禁用不必要的服务
    local unnecessary_services=(
        "bluetooth.service"
        "cups.service"
        "avahi-daemon.service"
        "ModemManager.service"
        "accounts-daemon.service"
        "rtkit-daemon.service"
    )
    
    for service in "${unnecessary_services[@]}"; do
        if systemctl is-enabled "$service" &> /dev/null; then
            systemctl disable "$service" &>> "$LOG_FILE"
            systemctl stop "$service" &>> "$LOG_FILE"
            print_msg "$YELLOW" "已禁用服务: $service"
        fi
    done
    
    # 优化系统日志
    if [ -f /etc/systemd/journald.conf ]; then
        sed -i 's/#SystemMaxUse=.*/SystemMaxUse=100M/' /etc/systemd/journald.conf
        sed -i 's/#SystemMaxFileSize=.*/SystemMaxFileSize=50M/' /etc/systemd/journald.conf
        systemctl restart systemd-journald
    fi
    
    # 优化SSH服务
    if [ -f /etc/ssh/sshd_config ]; then
        # 备份SSH配置
        cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
        
        # 优化SSH设置
        sed -i 's/#UseDNS.*/UseDNS no/' /etc/ssh/sshd_config
        sed -i 's/#TCPKeepAlive.*/TCPKeepAlive yes/' /etc/ssh/sshd_config
        sed -i 's/#ClientAliveInterval.*/ClientAliveInterval 60/' /etc/ssh/sshd_config
        sed -i 's/#ClientAliveCountMax.*/ClientAliveCountMax 3/' /etc/ssh/sshd_config
        
        systemctl restart sshd
        print_msg "$GREEN" "SSH服务优化完成"
    fi
    
    print_msg "$GREEN" "系统服务优化完成"
}

# 安全加固
security_hardening() {
    if [ "$OPTIMIZE_SECURITY" = false ]; then
        return
    fi
    
    print_msg "$BLUE" "\n执行安全加固..."
    
    # 设置命令历史记录安全
    cat >> /etc/profile << EOF

# Security: Command history settings
export HISTTIMEFORMAT="%F %T "
export HISTSIZE=1000
export HISTFILESIZE=1000
export HISTCONTROL=ignoreboth:erasedups
EOF
    
    # 设置登录超时
    cat >> /etc/profile << EOF

# Auto logout after 30 minutes of inactivity
TMOUT=1800
readonly TMOUT
export TMOUT
EOF
    
    # 限制su命令
    if [ -f /etc/pam.d/su ]; then
        sed -i 's/^#.*pam_wheel.so$/auth required pam_wheel.so use_uid/' /etc/pam.d/su
    fi
    
    # 设置密码策略
    if [ -f /etc/security/pwquality.conf ]; then
        cat >> /etc/security/pwquality.conf << EOF
# Password quality requirements
minlen = 8
dcredit = -1
ucredit = -1
ocredit = -1
lcredit = -1
EOF
    fi
    
    # 禁用不安全的内核模块
    cat > /etc/modprobe.d/blacklist-insecure.conf << EOF
# Disable insecure kernel modules
blacklist usb-storage
blacklist firewire-core
blacklist thunderbolt
EOF
    
    # 设置内核安全参数
    cat >> /etc/sysctl.d/99-security.conf << EOF
# Security hardening
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
kernel.yama.ptrace_scope = 1
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
EOF
    
    sysctl -p /etc/sysctl.d/99-security.conf &>> "$LOG_FILE"
    
    print_msg "$GREEN" "安全加固完成"
}

# CPU性能模式优化
optimize_cpu_performance() {
    print_msg "$BLUE" "\n优化CPU性能..."
    
    # 设置CPU性能模式
    if command -v cpupower &> /dev/null; then
        cpupower frequency-set -g performance &>> "$LOG_FILE"
        print_msg "$GREEN" "CPU已设置为性能模式"
    fi
    
    # 禁用CPU节能特性（适合性能优先的场景）
    if [ "$AUTO_MODE" = true ] || { read -p "是否禁用CPU节能特性以获得最佳性能？(y/N): " confirm && [[ "$confirm" =~ ^[Yy]$ ]]; }; then
        # 禁用Intel CPU节能
        if [ -f /sys/devices/system/cpu/intel_pstate/no_turbo ]; then
            echo 0 > /sys/devices/system/cpu/intel_pstate/no_turbo
        fi
        
        # 设置所有CPU核心为在线状态
        for cpu in /sys/devices/system/cpu/cpu[0-9]*; do
            if [ -f "$cpu/online" ]; then
                echo 1 > "$cpu/online" 2>/dev/null
            fi
        done
        
        print_msg "$GREEN" "CPU性能优化完成"
    fi
}

# 生成优化报告
generate_report() {
    local report_file="$LOG_DIR/optimize_report_$(date +%Y%m%d_%H%M%S).txt"
    
    cat > "$report_file" << EOF
================================================================================
                          系统优化报告
================================================================================
优化时间: $(date '+%Y-%m-%d %H:%M:%S')
系统信息: $OS_TYPE $OS_VERSION
主机名称: $(hostname)
内存大小: ${TOTAL_RAM}MB
CPU核心: ${CPU_CORES}
虚拟化: $([ "$IS_VIRTUAL" = true ] && echo "$VIRT_TYPE" || echo "物理机")
--------------------------------------------------------------------------------

优化项目:
$([ "$OPTIMIZE_KERNEL" = true ] && echo "✓ 内核参数优化")
$([ "$OPTIMIZE_NETWORK" = true ] && echo "✓ 网络设置优化")
$([ "$OPTIMIZE_FILESYSTEM" = true ] && echo "✓ 文件系统优化")
$([ "$OPTIMIZE_SERVICES" = true ] && echo "✓ 系统服务优化")
$([ "$OPTIMIZE_SECURITY" = true ] && echo "✓ 安全加固")
✓ 系统限制优化
✓ 内存管理优化
✓ CPU性能优化

配置备份: $CONFIG_BACKUP_DIR
日志文件: $LOG_FILE

注意事项:
1. 部分优化需要重启系统才能完全生效
2. 建议定期检查系统性能和稳定性
3. 如需回滚，可使用备份的配置文件

================================================================================
EOF
    
    print_msg "$GREEN" "\n优化报告已生成: $report_file"
}

# 优化验证
verify_optimization() {
    print_msg "$BLUE" "\n验证优化结果..."
    
    # 检查关键参数
    echo -e "${CYAN}当前系统参数:${NC}"
    
    # 检查文件描述符限制
    echo -e "文件描述符限制: $(ulimit -n)"
    
    # 检查TCP拥塞控制
    if [ -f /proc/sys/net/ipv4/tcp_congestion_control ]; then
        echo -e "TCP拥塞控制: $(cat /proc/sys/net/ipv4/tcp_congestion_control)"
    fi
    
    # 检查swappiness
    echo -e "Swappiness: $(cat /proc/sys/vm/swappiness)"
    
    # 检查IO调度器
    for device in $(lsblk -d -n -o NAME | grep -E '^(sd|vd|nvme)' | head -1); do
        if [ -f /sys/block/$device/queue/scheduler ]; then
            echo -e "IO调度器: $(cat /sys/block/$device/queue/scheduler)"
            break
        fi
    done
}

# 交互式菜单
interactive_menu() {
    clear
    echo -e "${PURPLE}╔════════════════════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${PURPLE}║                         VPS 系统优化工具 v1.0                              ║${NC}"
    echo -e "${PURPLE}╚════════════════════════════════════════════════════════════════════════════╝${NC}"
    echo ""
    echo -e "${CYAN}系统信息:${NC} $OS_TYPE $OS_VERSION | 内存: ${TOTAL_RAM}MB | CPU: ${CPU_CORES}核"
    echo ""
    echo -e "${CYAN}请选择优化选项:${NC}"
    echo ""
    echo -e "${GREEN}1)${NC} 一键优化（推荐）"
    echo -e "${GREEN}2)${NC} 性能优化（内核、网络、文件系统）"
    echo -e "${GREEN}3)${NC} 安全加固"
    echo -e "${GREEN}4)${NC} 自定义优化"
    echo -e "${GREEN}5)${NC} 查看当前系统参数"
    echo -e "${GREEN}0)${NC} 退出"
    echo ""
    read -p "请输入选项 [0-5]: " choice
    
    case $choice in
        1)
            backup_configs
            optimize_kernel_parameters
            optimize_network
            optimize_limits
            optimize_filesystem
            optimize_memory
            optimize_services
            security_hardening
            optimize_cpu_performance
            ;;
        2)
            backup_configs
            optimize_kernel_parameters
            optimize_network
            optimize_filesystem
            optimize_memory
            optimize_cpu_performance
            ;;
        3)
            backup_configs
            security_hardening
            ;;
        4)
            custom_optimize_menu
            ;;
        5)
            verify_optimization
            echo ""
            read -p "按回车键继续..."
            interactive_menu
            ;;
        0)
            print_msg "$YELLOW" "退出优化程序"
            exit 0
            ;;
        *)
            print_msg "$RED" "无效选项"
            sleep 2
            interactive_menu
            ;;
    esac
}

# 自定义优化菜单
custom_optimize_menu() {
    clear
    echo -e "${CYAN}自定义优化选项${NC}"
    echo ""
    
    local options=(
        "内核参数优化"
        "网络设置优化"
        "文件系统优化"
        "内存管理优化"
        "系统服务优化"
        "安全加固"
        "CPU性能优化"
    )
    
    for i in "${!options[@]}"; do
        echo -e "${GREEN}$((i+1)))${NC} ${options[$i]}"
    done
    
    echo ""
    echo -e "${YELLOW}输入要执行的优化编号（用空格分隔）:${NC}"
    read -p "> " input
    
    backup_configs
    
    for num in $input; do
        case $num in
            1) optimize_kernel_parameters ;;
            2) optimize_network ;;
            3) optimize_filesystem ;;
            4) optimize_memory ;;
            5) optimize_services ;;
            6) security_hardening ;;
            7) optimize_cpu_performance ;;
        esac
    done
}

# 解析命令行参数
parse_arguments() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            --auto|-a)
                AUTO_MODE=true
                shift
                ;;
            --network)
                OPTIMIZE_KERNEL=false
                OPTIMIZE_FILESYSTEM=false
                OPTIMIZE_SERVICES=false
                OPTIMIZE_SECURITY=false
                shift
                ;;
            --kernel)
                OPTIMIZE_NETWORK=false
                OPTIMIZE_FILESYSTEM=false
                OPTIMIZE_SERVICES=false
                OPTIMIZE_SECURITY=false
                shift
                ;;
            --security)
                OPTIMIZE_KERNEL=false
                OPTIMIZE_NETWORK=false
                OPTIMIZE_FILESYSTEM=false
                OPTIMIZE_SERVICES=false
                shift
                ;;
            --help|-h)
                show_help
                exit 0
                ;;
            *)
                print_msg "$RED" "未知选项: $1"
                show_help
                exit 1
                ;;
        esac
    done
}

# 显示帮助信息
show_help() {
    cat << EOF
使用方法: $0 [选项]

选项:
  --auto, -a      自动模式，执行所有优化
  --network       仅执行网络优化
  --kernel        仅执行内核优化
  --security      仅执行安全加固
  --help, -h      显示此帮助信息

示例:
  $0              # 交互式优化
  $0 --auto       # 自动执行所有优化
  $0 --network    # 仅优化网络设置
  $0 --security   # 仅执行安全加固

注意:
  - 此脚本需要root权限运行
  - 优化前会自动备份相关配置
  - 部分优化需要重启才能生效
EOF
}

# 主函数
main() {
    # 初始化
    create_directories
    check_root
    parse_arguments "$@"
    
    # 检测系统信息
    detect_system
    
    # 开始优化流程
    log "INFO" "开始系统优化流程"
    
    if [ "$AUTO_MODE" = true ]; then
        print_msg "$BLUE" "自动优化模式启动..."
        
        backup_configs
        optimize_kernel_parameters
        optimize_network
        optimize_limits
        optimize_filesystem
        optimize_memory
        optimize_services
        security_hardening
        optimize_cpu_performance
    else
        interactive_menu
    fi
    
    # 验证优化结果
    verify_optimization
    
    # 生成报告
    generate_report
    
    # 显示完成信息
    echo ""
    print_msg "$GREEN" "系统优化完成！"
    print_msg "$YELLOW" "\n注意: 某些优化可能需要重启系统才能完全生效"
    
    if [ "$AUTO_MODE" = false ]; then
        echo ""
        read -p "是否立即重启系统？(y/N): " reboot_confirm
        if [[ "$reboot_confirm" =~ ^[Yy]$ ]]; then
            print_msg "$YELLOW" "系统将在5秒后重启..."
            sleep 5
            reboot
        fi
    fi
}

# 运行主函数
main "$@"
