#!/bin/bash
#***************************************************************#
# ScriptName: k8simage.sh
# Author: xhy
# Create Date: 2025-02-10 23:51
# Modify Date: 2025-02-11 00:37
# Version: v2
#***************************************************************#

set -eo pipefail
trap 'echo -e "\033[31m[ERR]  $LINENO : $BASH_COMMAND\033[0m"; exit 1' ERR

# ================= 集群配置 =================
declare -a ALL_IPS=(
    172.24.8.111 172.24.8.112 172.24.8.113 
    172.24.8.114 172.24.8.115 172.24.8.116
)

declare -A IMAGE_MAP=(
    ["dashboard"]="docker.m.daocloud.io/kubernetesui/dashboard:v2.7.0"
    ["metrics-scraper"]="docker.m.daocloud.io/kubernetesui/metrics-scraper:v1.0.8"
    ["coredns"]="k8s.m.daocloud.io/coredns/coredns:v1.11.3"
    ["cluster-autoscaler"]="k8s.m.daocloud.io/cpa/cluster-proportional-autoscaler:v1.8.8"
    ["dns-node-cache"]="k8s.m.daocloud.io/dns/k8s-dns-node-cache:1.22.28"
    ["kube-apiserver"]="k8s.m.daocloud.io/kube-apiserver:v1.32.0"
    ["kube-controller"]="k8s.m.daocloud.io/kube-controller-manager:v1.32.0"
    ["kube-proxy"]="k8s.m.daocloud.io/kube-proxy:v1.32.0"
    ["kube-scheduler"]="k8s.m.daocloud.io/kube-scheduler:v1.32.0"
    ["metrics-server"]="k8s.m.daocloud.io/metrics-server/metrics-server:v0.7.0"
    ["pause"]="k8s.m.daocloud.io/pause:3.10"
    ["calico-cni"]="quay.m.daocloud.io/calico/cni:v3.29.1"
    ["calico-kubectl"]="quay.m.daocloud.io/calico/kube-controllers:v3.29.1"
    ["calico-node"]="quay.m.daocloud.io/calico/node:v3.29.1"
)

# ================= 全局配置 =================
IMAGES_DIR="/root/k8simages"
SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=15"

# ================= 日志函数 =================
log_info()  { echo -e "\033[34m[INFO] $*\033[0m"; }
log_succ()  { echo -e "\033[32m[SUCC] $*\033[0m"; }
log_error() { echo -e "\033[31m[ERROR] $*\033[0m" >&2; }

# ================= 安装 containerd =================
install_containerd() {
    for ip in "${ALL_IPS[@]}"; do
        log_info "正在安装 containerd: ${ip}"
        ssh $SSH_OPTS root@${ip} "yum -y install yum-utils device-mapper-persistent-data lvm2"
        ssh $SSH_OPTS root@${ip} "yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo"
        ssh $SSH_OPTS root@${ip} "sed -i 's+download.docker.com+mirrors.aliyun.com/docker-ce+' /etc/yum.repos.d/docker-ce.repo"
        ssh $SSH_OPTS root@${ip} "yum -y install containerd.io"
        ssh $SSH_OPTS root@${ip} "systemctl enable containerd --now"
    done
}

# ================= 镜像处理（拉取+导出）=================
handle_images() {
    log_info "开始处理容器镜像......"
    mkdir -p "${IMAGES_DIR}"
    
    for name in "${!IMAGE_MAP[@]}"; do
        local img="${IMAGE_MAP[$name]}"
        log_info "正在拉取: ${img}"
        ctr -n k8s.io images pull "${img}"
        
        # 生成安全文件名（替换特殊字符）
        local safe_name=$(echo "${img}" | sed 's/[\/:]/-/g')
        local tar_path="${IMAGES_DIR}/${safe_name}.tar"
        
        log_info "正在导出: ${tar_path}"
        ctr -n k8s.io images export "${tar_path}" "${img}"
    done
}

# ================= 集群文件分发 =================
distribute_files() {
    log_info "开始集群文件分发..."
    for ip in "${ALL_IPS[@]}"; do
        log_info "处理节点: ${ip}"
        ssh $SSH_OPTS root@${ip} "mkdir -p ${IMAGES_DIR} || { exit 1; }"
        rsync -avzP --timeout=30 -e "ssh $SSH_OPTS" \
            "${IMAGES_DIR}"/*.tar \
            root@${ip}:"${IMAGES_DIR}"/
    done
}

# ================= 集群镜像导入 =================
import_images() {
    log_info "开始集群镜像导入..."
    for ip in "${ALL_IPS[@]}"; do
        log_info "正在导入: ${ip}"
        ssh $SSH_OPTS root@${ip} \
            "find ${IMAGES_DIR} -name '*.tar' -print0 | xargs -0 -I{} ctr -n k8s.io images import {}"
    done
}

# ================= 主流程控制 =================
main() {
    install_containerd
    handle_images
    distribute_files
    import_images
    log_succ "所有操作已完成！"
}

# ================= 执行入口 =================
main

