#!/bin/sh

# Prompt user for the new root password
read -sp "请输入新的 root 密码: " new_password
echo

# Detect the OS type
if [ -f /etc/redhat-release ]; then
    # For CentOS/RHEL
    echo "检测到 CentOS/RHEL 系统。"
    
    # Stop iptables and disable it on boot
    sudo service iptables stop 2> /dev/null
    chkconfig iptables off 2> /dev/null

    # Disable SELinux
    sudo sed -i.bak '/^SELINUX=/cSELINUX=disabled' /etc/sysconfig/selinux
    sudo sed -i.bak '/^SELINUX=/cSELINUX=disabled' /etc/selinux/config
    sudo setenforce 0

    # Change the root password
    echo "root:$new_password" | sudo chpasswd

    # Enable root login and password authentication for SSH
    sudo sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config
    sudo sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/g' /etc/ssh/sshd_config
    sudo sed -i 's/^#\?Port 22/Port 22/g' /etc/ssh/sshd_config

elif [ -f /etc/lsb-release ]; then
    # For Ubuntu
    echo "检测到 Ubuntu 系统。"

    # Change the root password
    echo "root:$new_password" | sudo chpasswd

    # Enable root login and password authentication for SSH
    sudo sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config
    sudo sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/g' /etc/ssh/sshd_config
    sudo sed -i 's/^#\?Port 22/Port 22/g' /etc/ssh/sshd_config

    # Check if sshd_config.d directory exists and modify its contents
    if [ -d /etc/ssh/sshd_config.d ]; then
        sudo sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config.d/*
        sudo sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/g' /etc/ssh/sshd_config.d/*
        sudo sed -i 's/^#\?Port 22/Port 22/g' /etc/ssh/sshd_config.d/*
    fi

elif [ -f /etc/debian_version ]; then
    # For Debian
    echo "检测到 Debian 系统。"

    # Change the root password
    echo "root:$new_password" | sudo chpasswd

    # Enable root login and password authentication for SSH
    sudo sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config
    sudo sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/g' /etc/ssh/sshd_config

    # Check if sshd_config.d directory exists and modify its contents
    if [ -d /etc/ssh/sshd_config.d ]; then
        sudo sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config.d/*
        sudo sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/g' /etc/ssh/sshd_config.d/*
        sudo sed -i 's/^#\?Port 22/Port 22/g' /etc/ssh/sshd_config.d/*
    fi

else
    echo "不支持的操作系统。"
    exit 1
fi

# Restart SSH service
if [ -f /etc/init.d/sshd ]; then
    sudo service sshd restart
else
    sudo service ssh restart
fi

echo "配置已更新，root 密码已更改。"
