#!/bin/bash

# 颜色定义
RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
BLUE="\033[34m"
CYAN="\033[36m"
PURPLE="\033[35m"
WHITE="\033[37m"
BOLD="\033[1m"
UNDERLINE="\033[4m"
PLAIN="\033[0m"

# 检测系统类型函数
check_system() {
    if [ -f /etc/redhat-release ]; then
        OS="CentOS"
    elif [ -f /etc/lsb-release ]; then
        OS="Ubuntu"
    elif [ -f /etc/debian_version ]; then
        OS="Debian"
    else
        echo -e "${RED}[错误] 未识别的系统类型${PLAIN}"
        return 1
    fi
    echo -e "${GREEN}[信息] 检测到系统类型: ${OS}${PLAIN}"
    return 0
}

# 检查是否以root权限运行
check_root() {
    if [ "$(id -u)" != "0" ]; then
        echo -e "${RED}[错误] 此脚本需要以root权限运行${PLAIN}"
        echo -e "${YELLOW}请使用 sudo bash $0 重新运行${PLAIN}"
        exit 1
    fi
}

# 关闭并禁用防火墙函数
disable_firewall() {
    echo -e "${BLUE}[执行] 正在关闭并禁用防火墙...${PLAIN}"
    
    if ! check_system; then
        echo -e "${RED}[错误] 无法检测系统类型，防火墙操作失败${PLAIN}"
        return 1
    fi
    
    case $OS in
        "CentOS")
            systemctl stop firewalld
            systemctl disable firewalld
            ;;
        "Debian")
            systemctl stop ufw
            systemctl disable ufw
            ;;
        "Ubuntu")
            ufw disable
            systemctl disable ufw
            ;;
    esac
    
    echo -e "${GREEN}[成功] 防火墙已关闭并禁用开机自启${PLAIN}"
    return 0
}

# 安装和配置OpenSSH函数
install_openssh() {
    echo -e "${BLUE}[执行] 正在安装和配置OpenSSH...${PLAIN}"
    
    if ! check_system; then
        echo -e "${RED}[错误] 无法检测系统类型，OpenSSH安装失败${PLAIN}"
        return 1
    fi
    
    case $OS in
        "CentOS")
            yum install openssh-server -y
            ;;
        "Debian" | "Ubuntu")
            apt-get update
            apt-get install openssh-server -y
            ;;
    esac
    
    # 启动SSH服务
    systemctl start sshd
    
    # 设置SSH服务开机自启动
    systemctl enable sshd
    
    # 显示SSH服务状态
    systemctl status sshd
    
    echo -e "${GREEN}[成功] OpenSSH已安装并配置为在启动时自动启动${PLAIN}"
    return 0
}

# 修复远控SSH服务函数
fix_ssh() {
    echo -e "${BLUE}[执行] 正在修复远控SSH服务...${PLAIN}"
    
    if [ -e "/etc/ssh/sshd_config" ]; then
        # 检查是否已经存在PermitRootLogin设置
        if grep -q "^PermitRootLogin" /etc/ssh/sshd_config; then
            # 如果存在，则修改它
            sed -i 's/^PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config
            echo -e "${GREEN}[信息] 已更新PermitRootLogin设置为yes${PLAIN}"
        else
            # 如果不存在，则添加它
            sed -i '39 a PermitRootLogin yes' /etc/ssh/sshd_config
            echo -e "${GREEN}[信息] 已添加PermitRootLogin yes设置${PLAIN}"
        fi
        
        systemctl reload sshd
        echo -e "${GREEN}[成功] SSH服务已重新加载配置${PLAIN}"
    else
        echo -e "${RED}[错误] 在 /etc/ssh/ 目录下找不到 sshd_config 文件${PLAIN}"
        return 1
    fi
    
    return 0
}

# 安装SAMBA函数
install_samba() {
    echo -e "${BLUE}[执行] 正在安装和配置SAMBA...${PLAIN}"
    
    if ! check_system; then
        echo -e "${RED}[错误] 无法检测系统类型，SAMBA安装失败${PLAIN}"
        return 1
    fi
    
    # 根据操作系统类型执行不同的安装命令
    case $OS in
        "CentOS")
            yum -y install samba
            ;;
        "Ubuntu" | "Debian")
            apt-get update
            apt-get -y install samba
            ;;
        *)
            echo -e "${RED}[错误] 不支持的操作系统${PLAIN}"
            return 1
            ;;
    esac
    
    # 提示用户输入共享目录
    echo -e "${YELLOW}请输入需要共享的目录（不存在则会自动创建）：${PLAIN}"
    read -r share_dir
    
    # 验证输入不为空
    if [ -z "$share_dir" ]; then
        echo -e "${RED}[错误] 共享目录不能为空${PLAIN}"
        return 1
    fi
    
    mkdir -p "${share_dir}"
    chmod -R 777 "${share_dir}"
    
    # 提示用户输入共享的名称
    echo -e "${YELLOW}请输入共享的名称（别名）：${PLAIN}"
    read -r share_name
    
    # 验证输入不为空
    if [ -z "$share_name" ]; then
        echo -e "${RED}[错误] 共享名称不能为空${PLAIN}"
        return 1
    fi
    
    # 设置Samba的root密码
    echo -e "${YELLOW}请设置Samba的root密码：${PLAIN}"
    smbpasswd -a root
    
    # 添加共享目录配置到Samba配置文件
    tee -a /etc/samba/smb.conf <<EOF
[${share_name}]
   comment = ${share_name}
   path = ${share_dir}
   browseable = yes
   writeable = yes
   guest ok = yes
   read only = no
   valid users = root
EOF
    
    # 重启Samba服务
    case $OS in
        "CentOS")
            systemctl restart smb
            ;;
        "Ubuntu" | "Debian")
            service smbd restart
            ;;
    esac
    
    # 设置Samba开机自启动
    case $OS in
        "CentOS")
            systemctl enable smb
            ;;
        "Ubuntu" | "Debian")
            update-rc.d smbd enable
            ;;
    esac
    
    # 计算浏览器和Windows访问的URL
    ip_address=$(hostname -I | awk '{print $1}')
    browser_url="smb://${ip_address}/${share_name}"
    windows_url="\\\\${ip_address}\\${share_name}"
    
    echo -e "${GREEN}[成功] SAMBA已安装并配置完成${PLAIN}"
    echo -e "${GREEN}浏览器通过 \"${browser_url}\" 访问${PLAIN}"
    echo -e "${GREEN}Windows通过 \"${windows_url}\" 访问${PLAIN}"
    
    return 0
}

# 配置系统网络优化函数
optimize_network() {
    echo -e "${BLUE}[执行] 正在配置系统网络优化...${PLAIN}"
    
    # 备份当前的sysctl.conf
    cp /etc/sysctl.conf /etc/sysctl.conf.bak
    echo -e "${GREEN}[信息] 已备份原始配置到 /etc/sysctl.conf.bak${PLAIN}"
    
    # 删除现有的网络参数配置
    sed -i '/net.ipv4.tcp_retries2/d' /etc/sysctl.conf
    sed -i '/net.ipv4.tcp_slow_start_after_idle/d' /etc/sysctl.conf
    sed -i '/net.ipv4.tcp_fastopen/d' /etc/sysctl.conf
    sed -i '/fs.file-max/d' /etc/sysctl.conf
    sed -i '/fs.inotify.max_user_instances/d' /etc/sysctl.conf
    sed -i '/net.ipv4.tcp_syncookies/d' /etc/sysctl.conf
    sed -i '/net.ipv4.tcp_fin_timeout/d' /etc/sysctl.conf
    sed -i '/net.ipv4.tcp_tw_reuse/d' /etc/sysctl.conf
    sed -i '/net.ipv4.tcp_max_syn_backlog/d' /etc/sysctl.conf
    sed -i '/net.ipv4.ip_local_port_range/d' /etc/sysctl.conf
    sed -i '/net.ipv4.tcp_max_tw_buckets/d' /etc/sysctl.conf
    sed -i '/net.ipv4.route.gc_timeout/d' /etc/sysctl.conf
    sed -i '/net.ipv4.tcp_synack_retries/d' /etc/sysctl.conf
    sed -i '/net.ipv4.tcp_syn_retries/d' /etc/sysctl.conf
    sed -i '/net.core.somaxconn/d' /etc/sysctl.conf
    sed -i '/net.core.netdev_max_backlog/d' /etc/sysctl.conf
    sed -i '/net.ipv4.tcp_timestamps/d' /etc/sysctl.conf
    sed -i '/net.ipv4.tcp_max_orphans/d' /etc/sysctl.conf
    sed -i '/net.ipv4.ip_forward/d' /etc/sysctl.conf
    
    # 添加优化后的网络参数
    echo "# 网络性能优化参数 - $(date)" >> /etc/sysctl.conf
    echo "net.ipv4.tcp_retries2 = 8
net.ipv4.tcp_slow_start_after_idle = 0
fs.file-max = 1000000
fs.inotify.max_user_instances = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.route.gc_timeout = 100
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 1
net.core.somaxconn = 32768
net.core.netdev_max_backlog = 32768
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_max_orphans = 32768
# forward ipv4
#net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
    
    # 应用新的网络参数
    sysctl -p
    
    # 配置文件描述符限制
    echo "*               soft    nofile           1000000
*               hard    nofile          1000000" > /etc/security/limits.conf
    
    # 添加ulimit设置到profile
    echo "ulimit -SHn 1000000" >> /etc/profile
    
    echo -e "${GREEN}[成功] 系统网络参数已优化${PLAIN}"
    echo -e "${YELLOW}注意: 需要重启系统后，优化配置才能完全生效${PLAIN}"
    
    # 询问是否重启
    echo -e "${YELLOW}需要重启系统后，才能生效系统优化配置，是否现在重启? [Y/n]${PLAIN}"
    read -r yn
    [ -z "${yn}" ] && yn="y"
    if [[ $yn == [Yy] ]]; then
        echo -e "${GREEN}[信息] 系统将在3秒后重启...${PLAIN}"
        sleep 3
        reboot
    else
        echo -e "${YELLOW}[信息] 已取消重启，请记得稍后手动重启系统${PLAIN}"
    fi
    
    return 0
}

# 显示菜单函数
show_menu() {
    clear
    
    # 显示标题和装饰
    echo -e "${CYAN}╔═══════════════════════════════════════════════════════════╗${PLAIN}"
    echo -e "${CYAN}║${PLAIN} ${BOLD}${PURPLE}               PVE系统修复专用工具箱                 ${PLAIN} ${CYAN}║${PLAIN}"
    echo -e "${CYAN}╠═══════════════════════════════════════════════════════════╣${PLAIN}"
    
    # 菜单项
    echo -e "${CYAN}║${PLAIN} ${YELLOW}  1.${PLAIN} ${WHITE}关闭并禁用防火墙${PLAIN}${CYAN}${BOLD}${YELLOW}                        ${PLAIN}${CYAN}║${PLAIN}"
    echo -e "${CYAN}║${PLAIN} ${YELLOW}  2.${PLAIN} ${WHITE}安装和配置OpenSSH${PLAIN}${CYAN}${BOLD}${YELLOW}                     ${PLAIN}${CYAN}║${PLAIN}"
    echo -e "${CYAN}║${PLAIN} ${YELLOW}  3.${PLAIN} ${WHITE}修复远控SSH服务${PLAIN}${CYAN}${BOLD}${YELLOW}                     ${PLAIN}${CYAN}║${PLAIN}"
    echo -e "${CYAN}║${PLAIN} ${YELLOW}  4.${PLAIN} ${WHITE}安装和配置SAMBA${PLAIN}${CYAN}${BOLD}${YELLOW}                     ${PLAIN}${CYAN}║${PLAIN}"
    echo -e "${CYAN}║${PLAIN} ${YELLOW}  5.${PLAIN} ${WHITE}配置系统网络优化${PLAIN}${CYAN}${BOLD}${YELLOW}                     ${PLAIN}${CYAN}║${PLAIN}"
    echo -e "${CYAN}║${PLAIN} ${YELLOW}  0.${PLAIN} ${WHITE}退出${PLAIN}${CYAN}${BOLD}${YELLOW}                            ${PLAIN}${CYAN}║${PLAIN}"
    
    # 分隔线
    echo -e "${CYAN}╠═══════════════════════════════════════════════════════════╣${PLAIN}"
    
    # 提示输入
    echo -e "${CYAN}║${PLAIN} ${BOLD}${GREEN}请输入选择 [0-5]: ${PLAIN}${CYAN}${BOLD}${YELLOW}                    ${PLAIN}${CYAN}║${PLAIN}"
    
    # 底部边框
    echo -e "${CYAN}╚═══════════════════════════════════════════════════════════╝${PLAIN}"
}

# 主函数
main() {
    check_root
    
    while true; do
        show_menu
        read -r choice
        
        case $choice in
            1)
                disable_firewall
                ;;
            2)
                install_openssh
                ;;
            3)
                fix_ssh
                ;;
            4)
                install_samba
                ;;
            5)
                optimize_network
                ;;
            0)
                clear
                echo -e "${CYAN}╔═══════════════════════════════════════════════════════════╗${PLAIN}"
                echo -e "${CYAN}║${PLAIN} ${BOLD}${GREEN}        感谢使用 PVE系统修复专用工具箱！         ${PLAIN} ${CYAN}║${PLAIN}"
                echo -e "${CYAN}║${PLAIN} ${BOLD}${GREEN}                  再见！                  ${PLAIN} ${CYAN}║${PLAIN}"
                echo -e "${CYAN}╚═══════════════════════════════════════════════════════════╝${PLAIN}"
                sleep 1
                exit 0
                ;;
            *)
                echo -e "${RED}[错误] 无效的选择，请重新输入${PLAIN}"
                sleep 1
                ;;
        esac
        
        # 按任意键返回菜单
        echo -e "\n${YELLOW}${BOLD}按任意键返回菜单...${PLAIN}"
        read -r -n 1
    done
}

# 执行主函数
main