#!/bin/bash

# 确保以 root 用户或具有 sudo 权限的用户运行此脚本

# 1. 修改镜像源并更新系统
echo "Updating mirror sources and system..."
dnf config-manager --set-enabled crb
dnf install -y epel-release

# 修改 Rocky Linux 和 EPEL 源为阿里云镜像
sed -i.bak -e 's|^mirrorlist=|#mirrorlist=|g' \
           -e 's|^#baseurl=http://dl.rockylinux.org/$contentdir|baseurl=https://mirrors.aliyun.com/rockylinux|g' \
           /etc/yum.repos.d/[Rr]ocky*.repo

sed -i.bak -e 's|^metalink=|#metalink=|g' \
           -e 's|^#baseurl=https://download.example/pub|baseurl=https://mirrors.aliyun.com|g' \
           /etc/yum.repos.d/epel{,-testing}.repo

dnf clean all
dnf makecache
dnf -y update

# 2. 修改 SSH 端口和防火墙设置
echo "Configuring SSH and firewall..."
sed -i 's/#Port 22/Port 12123/' /etc/ssh/sshd_config
firewall-cmd --zone=public --add-port=12123/tcp --permanent
firewall-cmd --reload

# 禁用 SELinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config

# 3. 安装 Docker
echo "Installing Docker..."
dnf install -y yum-utils
yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
dnf install -y docker-ce docker-ce-cli containerd.io

# 配置 Docker 加速器
mkdir -p /etc/docker
cat > /etc/docker/daemon.json <<EOF
{
    "registry-mirrors": [
        "https://eihzr0te.mirror.aliyuncs.com",
        "https://reg.infosilo.tech",
        "https://dockerpull.com",
        "https://docker.anyhub.us.kg",
        "https://dockerhub.jobcher.com"
    ],
    "max-concurrent-downloads": 10,
    "max-concurrent-uploads": 5,
    "log-driver": "json-file",
    "log-opts": {
        "max-file": "3",
        "max-size": "500m"
    },
    "live-restore": true
}
EOF

systemctl daemon-reload
systemctl enable --now docker

# 4. 配置网络流量转发
echo "Configuring network forwarding..."
echo "br_netfilter" > /etc/modules-load.d/br_netfilter.conf
chmod 755 /etc/modules-load.d/br_netfilter.conf

cat > /etc/sysctl.d/docker.conf <<EOF
net.bridge.bridge-nf-call-ip6tables=1
net.bridge.bridge-nf-call-iptables=1
net.bridge.bridge-nf-call-arptables=1
net.ipv4.ip_forward=1
EOF

sysctl --system

# 重启系统
echo "Rebooting the system..."
reboot
