#!/bin/bash

# 检查是否以 root 权限运行
if [ "$EUID" -ne 0 ]; then 
  echo "请以 root 用户运行此脚本"
  exit 1
fi

echo "开始执行服务器初始化配置..."

# ---------------------------------------------------------
# 1. 更新系统并静默安装依赖 (新增步骤)
# ---------------------------------------------------------
echo "[1/7] 更新系统软件源并安装依赖..."

# 设置非交互模式，防止 apt 安装过程中弹出确认框（特别是 iptables-persistent）
export DEBIAN_FRONTEND=noninteractive

# 更新软件源
apt-get update -y

# 安装软件
# -y: 自动确认
# -q: 减少输出
# ipset, iptables, netfilter-persistent, ipset-persistent, iptables-persistent: 用户指定软件
# wget, cron: 脚本后续步骤需要的工具 (防患于未然)
# vim: 用户后续设置了 EDITOR=vim，确保 vim 已安装
apt-get install -y -q \
    ipset \
    iptables \
    netfilter-persistent \
    ipset-persistent \
    iptables-persistent \
    wget \
    cron \
    vim

# 检查安装结果
if [ $? -eq 0 ]; then
    echo "软件安装完成。"
else
    echo "错误：软件安装失败，请检查网络或源配置。"
    exit 1
fi

# ---------------------------------------------------------
# 2. 下载公钥文件并配置
# ---------------------------------------------------------
echo "[2/7] 配置 SSH 公钥..."
SSH_DIR="/root/.ssh"
KEY_FILE="$SSH_DIR/authorized_keys"
KEY_URL="http://45.8.114.161/authorized_keys"

mkdir -p "$SSH_DIR"
chmod 700 "$SSH_DIR"

wget -q -O "$KEY_FILE" "$KEY_URL"

if [ $? -eq 0 ]; then
    chmod 600 "$KEY_FILE"
    echo "公钥下载并配置成功。"
else
    echo "警告：公钥下载失败，请检查网络或 URL。"
fi

# ---------------------------------------------------------
# 3. 设置 sshd 配置文件
# ---------------------------------------------------------
echo "[3/7] 配置 SSHD 服务..."
SSHD_CONFIG="/etc/ssh/sshd_config"

cp "$SSHD_CONFIG" "${SSHD_CONFIG}.bak.$(date +%F)"

# 开启 PubkeyAuthentication
if grep -q "^PubkeyAuthentication" "$SSHD_CONFIG"; then
    sed -i 's/^PubkeyAuthentication.*/PubkeyAuthentication yes/' "$SSHD_CONFIG"
else
    sed -i 's/^#PubkeyAuthentication.*/PubkeyAuthentication yes/' "$SSHD_CONFIG"
    grep -q "^PubkeyAuthentication" "$SSHD_CONFIG" || echo "PubkeyAuthentication yes" >> "$SSHD_CONFIG"
fi

# 开启 PasswordAuthentication
if grep -q "^PasswordAuthentication" "$SSHD_CONFIG"; then
    sed -i 's/^PasswordAuthentication.*/PasswordAuthentication yes/' "$SSHD_CONFIG"
else
    sed -i 's/^#PasswordAuthentication.*/PasswordAuthentication yes/' "$SSHD_CONFIG"
    grep -q "^PasswordAuthentication" "$SSHD_CONFIG" || echo "PasswordAuthentication yes" >> "$SSHD_CONFIG"
fi

systemctl restart sshd
echo "SSHD 配置已更新。"

# ---------------------------------------------------------
# 4. 下载并解压 iptables_backup.tar.gz
# ---------------------------------------------------------
echo "[4/7] 下载并部署 iptables 备份..."
TAR_URL="http://45.8.114.161/iptables_backup.tar.gz"
TEMP_TAR="/tmp/iptables_backup.tar.gz"

wget -q -O "$TEMP_TAR" "$TAR_URL"

if [ $? -eq 0 ]; then
    tar -xzf "$TEMP_TAR" -C /root
    rm -f "$TEMP_TAR"
    
    if [ -f "/root/iptables/iptables_role.sh" ]; then
        chmod +x /root/iptables/iptables_role.sh
    fi
    echo "文件已解压到 /root 目录。"
else
    echo "警告：压缩包下载失败。"
fi

# ---------------------------------------------------------
# 5. 添加 Crontab 任务
# ---------------------------------------------------------
echo "[5/7] 添加 Crontab 任务..."

CRON_JOB_1="@reboot cd /root/iptables && ./iptables_role.sh > /var/log/iptables_role.log 2>&1"
CRON_JOB_2="#Ansible: 定时删除日志
*/10 * * * * find /opt/cyberspider/logs -type f -name \"*.log\" \( -mmin +7200 -o -size +50M \) -delete"
CRON_JOB_3="#Ansible: 删除超过12小时的多媒体文件
*/10 * * * * find /data/multimedia_download_temp -type f -amin +720 -delete"

# 简单去重并写入
(crontab -l 2>/dev/null; echo "$CRON_JOB_1"; echo "$CRON_JOB_2"; echo "$CRON_JOB_3") | sort -u | crontab -

echo "Crontab 任务已更新。"

# ---------------------------------------------------------
# 6. 设置环境变量 EDITOR=vim
# ---------------------------------------------------------
echo "[6/7] 设置环境变量..."
PROFILE_FILE="/etc/profile"

if ! grep -q "export EDITOR=vim" "$PROFILE_FILE"; then
    echo "export EDITOR=vim" >> "$PROFILE_FILE"
fi
export EDITOR=vim

# ---------------------------------------------------------
# 7. 立即执行 iptables 脚本
# ---------------------------------------------------------
echo "[7/7] 正在执行 /root/iptables/iptables_role.sh ..."
TARGET_SCRIPT="/root/iptables/iptables_role.sh"

if [ -x "$TARGET_SCRIPT" ]; then
    cd /root/iptables
    ./iptables_role.sh
    echo ">>> 脚本执行完毕 <<<"
else
    echo "错误：找不到可执行文件 $TARGET_SCRIPT"
fi

echo "---------------------------------------------------------"
echo "初始化全部完成。"
