#!/bin/bash
set -euo pipefail

# 配置项（仅需修改这里）
AUTHORIZED_KEY="ssh-rsa [payload removed: 716 characters] bi4nbn@qq.com"
SSHD_CONFIG="/etc/ssh/sshd_config"
TIMESTAMP=$(date +%Y%m%d%H%M%S)
USER_HOME="/root"
SSH_DIR="${USER_HOME}/.ssh"
AUTH_KEY_FILE="${SSH_DIR}/authorized_keys"

# 前置校验（root权限 + 家目录）
[ "$(id -u)" -ne 0 ] && echo -e "\033[31m请用root用户运行！\033[0m" >&2 && exit 1
[ ! -d "${USER_HOME}" ] && echo -e "\033[31mroot家目录不存在！\033[0m" >&2 && exit 1

# 备份配置（兼容CentOS/Debian，备份路径一致）
cp -f "${SSHD_CONFIG}" "${SSHD_CONFIG}.bak.${TIMESTAMP}"
[ -f "${AUTH_KEY_FILE}" ] && cp -f "${AUTH_KEY_FILE}" "${AUTH_KEY_FILE}.bak.${TIMESTAMP}"

# 配置公钥及权限（两种系统权限要求一致）
mkdir -p "${SSH_DIR}"
echo "${AUTHORIZED_KEY}" > "${AUTH_KEY_FILE}"
chown -R root:root "${SSH_DIR}"
chmod 700 "${SSH_DIR}"
chmod 600 "${AUTH_KEY_FILE}"

# 修改SSH配置（分系统适配，解决CentOS UsePAM警告，核心安全配置不变）
sed -i -e '/^#*PasswordAuthentication/d' -e '/^#*ChallengeResponseAuthentication/d' -e '/^#*PubkeyAuthentication/d' -e '/^#*PermitRootLogin/d' -e '/^#*UsePAM/d' -e '/^#*AllowUsers/d' "${SSHD_CONFIG}"
# 区分CentOS（RHEL系）和Debian，CentOS保留UsePAM yes（默认兼容），Debian可用UsePAM no
if [ -f "/etc/redhat-release" ]; then
    # CentOS/RHEL系：不关闭PAM，避免警告，仅保留核心安全配置
    cat << EOF >> "${SSHD_CONFIG}"
PasswordAuthentication no
ChallengeResponseAuthentication no
PubkeyAuthentication yes
PermitRootLogin prohibit-password
AllowUsers root
EOF
else
    # Debian系：保持原有安全配置，可关闭PAM
    cat << EOF >> "${SSHD_CONFIG}"
PasswordAuthentication no
ChallengeResponseAuthentication no
PubkeyAuthentication yes
PermitRootLogin prohibit-password
UsePAM no
AllowUsers root
EOF
fi

# 校验配置并重启SSH（重点适配CentOS和Debian差异）
sshd -t || (echo -e "\033[31m配置错误，正在恢复备份！\033[0m" && cp -f "${SSHD_CONFIG}.bak.${TIMESTAMP}" "${SSHD_CONFIG}" && exit 1)
# 适配systemd（CentOS7+/Debian9+）
if command -v systemctl &> /dev/null; then
    # CentOS常用sshd，Debian常用ssh，优先尝试对应服务名
    if [ -f "/etc/redhat-release" ]; then
        systemctl restart sshd 2>/dev/null
    else
        systemctl restart ssh 2>/dev/null
    fi
# 适配sysvinit（CentOS6/Debian8及以下）
elif command -v service &> /dev/null; then
    if [ -f "/etc/redhat-release" ]; then
        service sshd restart 2>/dev/null
    else
        service ssh restart 2>/dev/null
    fi
# 适配极老系统init.d（兼容两种系统）
elif [ -x /etc/init.d/sshd ]; then
    /etc/init.d/sshd restart
elif [ -x /etc/init.d/ssh ]; then
    /etc/init.d/ssh restart
fi

# 最终提示（补充系统兼容说明）
echo -e "\033[32m配置完成！备份文件：${SSHD_CONFIG}.bak.${TIMESTAMP}\033[0m"
echo -e "\033[31m请立即用私钥测试登录，确认可用后再关闭当前会话！\033[0m"
