#!/bin/bash
# 一键部署 阿里 yum 源 + Docker + K8s 脚本
# version: v1.5.0
# date: 2024-10-22
# update on 2024.12.26
# author: アニつり a.k.a AnitsuriW

# 指定运行日志的函数
LOG_FILE="/var/log/AliYUM+Docker+K8s.log"

# 让日志带时间的函数
log_echo() {
    local message="$1"
    local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    echo "$timestamp - $message" | tee -a $LOG_FILE
}

# 设置颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

# 打印带有颜色的标题
print_title() {
    local message="$1"

    # 打印彩色输出到终端
    echo -e "${GREEN}==================================================${NC}"
    echo -e "${GREEN}$message${NC}"
    echo -e "${GREEN}==================================================${NC}"

    # 将消息记录到日志文件中（不带颜色）
    log_echo "$message"
}


# 定义一个函数来运行 yum 并在失败时重试
run_yum() {
    local yum_command="$1"
    local service_name="$2"
    local max_retries=5
    local retry_count=0
    local yum_pid_file="/var/run/yum.pid"
    
    while [ $retry_count -lt $max_retries ]; do
        # 检查是否存在 yum 锁文件
        if [ -f "$yum_pid_file" ]; then
            local yum_pid=$(cat "$yum_pid_file")
            if ps -p $yum_pid > /dev/null 2>&1; then
                log_echo "另一个应用程序（PID: $yum_pid）正在持有 yum 锁，正在强制终止该进程..."
                sudo kill -9 "$yum_pid"  # 强制终止 yum 进程
                sudo rm -f "$yum_pid_file"  # 移除锁文件
                log_echo "已强制终止持有 yum 锁的进程并移除锁文件。"
            else
                log_echo "检测到 yum 锁文件，但进程 $yum_pid 已不存在，移除锁文件..."
                sudo rm -f "$yum_pid_file"
            fi
        fi
        
        # 尝试运行 yum 命令
        if $yum_command; then
            log_echo "$service_name 安装成功。"
            return 0  # 成功执行，退出函数
        else
            retry_count=$((retry_count+1))
            log_echo "yum 命令 '$yum_command' 失败，重试第 $retry_count 次..."
            sleep 5  # 等待 5 秒后重试
        fi
    done

    log_echo "yum 命令 '$yum_command' 多次失败，请检查网络连接或其他问题。"
    exit 1
}

print_title "欢迎"
log_echo "欢迎使用一键部署 阿里 yum 源 + Docker + K8s 脚本"
log_echo "使用本脚本前，请确保目前的网络环境能访问国际互联网"
log_echo "那么我们开始吧"

# 询问用户想要安装的 K8s 版本
print_title "设置 K8s 版本"
echo "目前最新版 K8s 是 Kubernetes v1.31"
read -p "首先，您想要安装的 Kubernetes 版本是：" k8s_version
log_echo "好的，这就为您准备 ${k8s_version} 版本的 K8s"

# 询问用户是否为 master 节点或 node 节点
read -p "请问这台机器是 K8s 的 master 节点还是 node 节点？(输入 master 或 node): " node_type
ipaddress=$(ip addr show | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}' | cut -d'/' -f1 | head -n 1)
log_echo "检测到的IP地址为: $ipaddress"


echo "接下来，让我们开始吧"
sleep 3s

# 检查防火墙状态并根据情况停止防火墙
print_title "检查防火墙"
log_echo "正在检查防火墙状态..."
firewalld_status=$(systemctl is-active firewalld)

if [ "$firewalld_status" == "active" ]; then
    log_echo "防火墙正在运行，正在停止防火墙..."
    sudo systemctl stop firewalld
    sudo systemctl disable firewalld
    log_echo "防火墙已停止并禁用。"
else
    log_echo "防火墙是关闭的。"
fi

# 关闭 swap
log_echo "正在禁用 swap"
sudo swapoff -a
sudo sed -i '/*.swap.*/$&/' /etc/fstab


# 检查yum源是否包含 mirrors.aliyun.com
print_title "检查 yum 源"
yum_repolist=$(yum repolist | grep "mirrors.aliyun.com")

if [ -z "$yum_repolist" ]; then
    log_echo "未找到阿里云源，让我们配置阿里云 yum 源..."

    # 检查是否已安装epel-release
    epel_installed=$(rpm -qa | grep epel-release)

    sudo mkdir -p /etc/yum.repos.d/backup
    sudo mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/
    
    sudo touch /etc/yum.repos.d/CentOS7-Aliyun.repo
    sudo bash -c 'cat > /etc/yum.repos.d/CentOS7-Aliyun.repo << EOF
[base]
name=CentOS-\$releasever - Base - mirrors.aliyun.com
baseurl=http://mirrors.aliyun.com/centos/\$releasever/os/\$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7

[updates]
name=CentOS-\$releasever - Updates - mirrors.aliyun.com
baseurl=http://mirrors.aliyun.com/centos/\$releasever/updates/\$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7

[extras]
name=CentOS-\$releasever - Extras - mirrors.aliyun.com
baseurl=http://mirrors.aliyun.com/centos/\$releasever/extras/\$basearch/
gpgcheck=1
gpgkey=http://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-7
EOF'

    run_yum "sudo yum clean all" "一键清除所有 yum 源"
    run_yum "sudo yum repolist" "阿里 yum 源"

    # 如果已安装epel-release，先卸载它
    if [ -n "$epel_installed" ]; then
        log_echo "检测到已安装epel-release，让我们先移除它..."
        run_yum "sudo yum remove -y epel-release" "EPEL 卸载成功，并没有"
    fi

    # 重新安装epel-release
    run_yum "sudo yum install -y epel-release" "epel-release"
    run_yum "sudo yum repolist" "所有的 yum 源都"
else
    log_echo "阿里云源已存在，跳过配置。"
fi

# 清空 iptables 规则
print_title "清空 Iptables 规则"
log_echo "正在清空 iptables 规则"
sudo iptables -F
sudo iptables -nvL

"""
# 暂时没用的代码

# 检查并切换到 iptables-legacy 模式
print_title "检查&切换 iptables 模式"
log_echo "正在检查 iptables 模式..."
CURRENT_MODE=$(sudo update-alternatives --display iptables | grep "current" | awk '{print $3}')
if [[ "$CURRENT_MODE" == *"iptables-legacy"* ]]; then
    log_echo "iptables 已经是 legacy 模式"
else
    log_echo "正在切换 iptables 到 legacy 模式..."
    sudo update-alternatives --set iptables /usr/sbin/iptables-legacy
    sudo update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy
    sudo update-alternatives --set arptables /usr/sbin/arptables-legacy
    sudo update-alternatives --set ebtables /usr/sbin/ebtables-legacy
    log_echo "iptables 已经切换到 legacy 模式"
fi


# 加载 br_netfilter 模块
if lsmod | grep "br_netfilter" &> /dev/null ; then
    log_echo "br_netfilter module 已被加载"
else
    log_echo "正在加载 br_netfilter 模块..."
    sudo modprobe br_netfilter
    log_echo "br_netfilter 模块 已加载"
fi
"""

# 设置内核参数以持久化配置
log_echo "设定内核参数 for Kubernetes..."
cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-iptables = 1
# net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF

# 应用 sysctl 配置
sudo sysctl --system

echo "1" > /proc/sys/net/ipv4/ip_forward && sed -i '/net.ipv4.ip_forward/d' /etc/sysctl.conf && echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf && sysctl -p

log_echo "所有配置已被成功应用"

# 检查是否安装 sshpass
if ! command -v sshpass &> /dev/null; then
    echo "sshpass 未安装，正在安装 sshpass..."
    run_yum "sudo yum install -y sshpass" "sshpass"
fi

# 时间同步
print_title "使时间同步"
log_echo "正在使时间同步......"
run_yum "sudo yum install -y chrony" "chrony"
sudo systemctl enable --now chronyd

# 安装Docker
print_title "部署 Docker"
log_echo "让我们来安装Docker..."
run_yum "sudo yum install -y yum-utils device-mapper-persistent-data lvm2" "yum-utils device-mapper-persistent-data lvm2"
run_yum "sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo" "阿里 Docker 源"
run_yum "sudo yum install -y docker-ce docker-ce-cli docker-buildx-plugin docker-compose-plugin containerd.io" "docker-ce docker-ce-cli docker-buildx-plugin docker-compose-plugin containerd.io"

# 配置Docker加速器
log_echo "让我们来配置Docker加速器..."
sudo mkdir -p /etc/docker
sudo cat <<EOF > /etc/docker/daemon.json
{
  "registry-mirrors": [
    "https://dockerhub.icu",
    "https://docker.chenby.cn",
    "https://docker.1panel.live",
    "https://docker.awsl9527.cn",
    "https://docker.anyhub.us.kg",
    "https://dhub.kubesre.xyz",
    "https://docker.registry.cyou",
    "https://docker-cf.registry.cyou",
    "https://dockercf.jsdelivr.fyi",
    "https://docker.jsdelivr.fyi",
    "https://dockertest.jsdelivr.fyi",
    "https://mirror.aliyuncs.com",
    "https://dockerproxy.com",
    "https://mirror.baidubce.com",
    "https://docker.m.daocloud.io",
    "https://docker.nju.edu.cn",
    "https://docker.mirrors.sjtug.sjtu.edu.cn",
    "https://docker.mirrors.ustc.edu.cn",
    "https://mirror.iscas.ac.cn",
    "https://docker.rainbond.c"
  ]
}
EOF

sudo systemctl daemon-reload
sudo systemctl start docker
sudo systemctl enable docker

# 配置 containerd
print_title "配置 containered"
log_echo "正在配置 containered"
sudo mkdir -p /etc/containerd
sudo containerd config default > /etc/containerd/config.toml
sudo sed -i '/SystemdCgroup/s/false/true/' /etc/containerd/config.toml
sudo systemctl enable --now containerd
log_echo "已配置好 containered"


# 部署 K8s
print_title "安装 K8s"
log_echo "正在安装 ${k8s_version} 版本的 Kubernetes"

cat <<EOF | sudo tee /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://pkgs.k8s.io/core:/stable:/v${k8s_version}/rpm/
enabled=1
gpgcheck=1
gpgkey=https://pkgs.k8s.io/core:/stable:/v${k8s_version}/rpm/repodata/repomd.xml.key
exclude=kubelet kubeadm kubectl cri-tools kubernetes-cni
EOF

run_yum "sudo yum install -y kubelet kubeadm kubectl --disableexcludes=kubernetes" "kubelet kubeadm kubectl"

echo 'KUBELET_CGROUP_ARGS="--cgroup-driver=systemd"' >> /etc/sysconfig/kubelet
sudo systemctl restart containerd
sudo systemctl daemon-reload

sudo systemctl enable --now kubelet
log_echo "已安装好 ${k8s_version} 版本的 Kubernetes"
log_echo "正在配置 ${k8s_version} 版本的 Kubernetes 的 master 节点"

# 判断节点类型
if [ "$node_type" == "master" ]; then

    kubeadm_init_output=$(kubeadm init \
        --pod-network-cidr=10.244.0.0/16 \
        --service-cidr=10.96.0.0/12 \
        --apiserver-advertise-address=${ipaddress} 2>&1 | tee -a $LOG_FILE)

    sudo mkdir -p $HOME/.kube
    sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
    sudo chown $(id -u):$(id -g) $HOME/.kube/config
    sudo export KUBECONFIG=/etc/kubernetes/admin.conf

    log_echo "K8s配置完成，请输入以下命令查看加入 node 节点的命令：tail -5 ${LOG_FILE}"
    log_echo "K8s配置完成，请输入以下命令配置网络插件Flannel：kubectl apply -f https://github.com/flannel-io/flannel/releases/latest/download/kube-flannel.yml"

 
fi
