#!/bin/bash
#***************************************************************#
# ScriptName: docker_pull_lists_images.sh
# Author: xhy
# Create Date: 2025-03-26 15:22
# Modify Author: xhy
# Modify Date: 2025-03-31 14:08
# Version: v1
#***************************************************************#

# 定义镜像列表文件路径
IMAGE_LIST_FILE="$(dirname "$0")/images.list"

# 定义国内镜像 URL 
INURL=uhub.service.ucloud.cn/imxhy

# 检查镜像列表文件是否存在
if [[ ! -f "${IMAGE_LIST_FILE}" ]]; then
    echo -e "\033[31m[ERROR] 镜像列表文件 ${IMAGE_LIST_FILE} 不存在!!！\033[0m" >&2
    exit 1
fi

# 拉取并重命名镜像
pull_and_rename() {
    # 读取镜像列表文件（跳过空行和注释）
    mapfile -t images < <(grep -vE '^#|^$' "${IMAGE_LIST_FILE}")
    
    for image in "${images[@]}"; do
        # 提取镜像名称和标签
        original_tag="${image}"
        image_name=$(echo "${image}" | awk -F':' '{print $1}')
        tag=$(echo "${image}" | awk -F':' '{print $2}')
        
        # 提取镜像名称最后一段作为UCloud镜像名
        ucloud_image_name=$(basename "${image_name}")
        
        # 构造UCloud镜像地址
        ucloud_image="${INURL}/${ucloud_image_name}:${tag}"
        
        echo -e "\n\033[33m[INFO] 正在下载 ${image} 镜像...\033[0m"
        
        # 拉取UCloud镜像
        if ! ctr -n k8s.io images pull "${ucloud_image}"; then
            echo -e "\033[31m[ERROR] ${ucloud_image} 下载失败...\033[0m"
            continue
        fi
        
        # 重新打回原始标签
        ctr -n k8s.io images tag "${ucloud_image}" "${original_tag}"
        
        # 删除UCloud镜像
        ctr -n k8s.io images rm "${ucloud_image}"
        
        echo -e "\n\033[32m[SUCC] 当前 ${original_tag} 镜像已下载完成...\033[0m"

        echo "-----------------------------------------"
    done
}

# 检查镜像存在性
check_existence() {
    declare -A local_images
    while IFS=: read -r repo tag; do
        image_base=$(basename "${repo}")
        local_images["${image_base}:${tag}"]=1
    done < <(crictl images --digests | awk '{print $1":"$2}' | grep -v '<none>')

    echo -e "\n\033[33m[CHECK] 镜像上传结果检查...\033[0m"

    mapfile -t target_images < <(grep -vE '^#|^$' "${IMAGE_LIST_FILE}")
    for image in "${target_images[@]}"; do
        image_base=$(basename "$(echo "${image}" | awk -F':' '{print $1}')")
        image_tag=$(echo "${image}" | awk -F':' '{print $2}')
        lookup_key="${image_base}:${image_tag}"

        if [[ -n "${local_images[${lookup_key}]}" ]]; then
            echo -e "\033[32m[EXIST] ${image} is exist...\033[0m"
        else
            echo -e "\033[31m[MISSING] ${image} is not exist...\033[0m"
        fi
    done
}

main() {
    # 执行拉取操作
    pull_and_rename
    
    # 执行检查操作
    check_existence
}

main "$@"
