#!/bin/bash

# 检查rsyslog是否已安装，如果未安装则进行安装
if ! dpkg -s rsyslog >/dev/null 2>&1; then
    echo "rsyslog未安装，开始安装..."
    apt update
    apt install -y rsyslog
    if [ $? -eq 0 ]; then
        echo "rsyslog安装成功。"
    else
        echo "rsyslog安装失败，请检查网络或手动安装。"
        exit 1
    fi
fi

# 创建rsyslog配置文件
config_file="/etc/rsyslog.d/99-custom.conf"
echo "创建并配置 $config_file..."
cat << EOF > $config_file
# 启用 /var/log/messages
*.info;mail.none;authpriv.none;cron.none /var/log/messages

# 启用 /var/log/secure
auth,authpriv.* /var/log/secure
EOF

# 检查配置文件是否创建成功
if [ -f $config_file ]; then
    echo "$config_file 创建成功。"
else
    echo "$config_file 创建失败，请手动检查。"
    exit 1
fi

# 重启rsyslog服务
echo "重启rsyslog服务..."
systemctl restart rsyslog
if [ $? -eq 0 ]; then
    echo "rsyslog服务重启成功。"
else
    echo "rsyslog服务重启失败，请手动检查。"
    exit 1
fi

# 等待一段时间让日志生成
sleep 5

# 输出/var/log/messages的前两条日志
echo "以下是 /var/log/messages 的前两条日志："
if [ -f "/var/log/messages" ]; then
    head -n 2 /var/log/messages
else
    echo "/var/log/messages 文件不存在。"
fi

# 输出/var/log/secure的前两条日志
echo "以下是 /var/log/secure 的前两条日志："
if [ -f "/var/log/secure" ]; then
    head -n 2 /var/log/secure
else
    echo "/var/log/secure 文件不存在。"
fi

echo "已成功启用 /var/log/messages 和 /var/log/secure。"
