#!/bin/bash
#***************************************************************#
# ScriptName: js_pull_lists_images.sh
# Author: xhy
# Create Date: 2025-12-12 14:12
# Modify Author: xhy
# Modify Date: 2025-12-12 14:14
# Version: v1
#***************************************************************#
set -euo pipefail

#================= 可配置参数 =================
# 镜像列表文件，一行一个完整镜像（含 tag）
IMAGES_LIST="${IMAGES_LIST:-images.list}"

# 运行时：docker 或 containerd
RUNTIME="${RUNTIME:-containerd}"

# 加速器前缀域名（不含协议，不含尾部 /）
SPEEDSERVER="${SPEEDSERVER:-js.linuxsb.com}"

# containerd 命名空间
CONTAINERD_NS="${CONTAINERD_NS:-k8s.io}"
#================================================

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
}

die() {
    echo "ERROR: $*" >&2
    exit 1
}

check_runtime() {
    case "$RUNTIME" in
        docker)
            command -v docker >/dev/null 2>&1 || die "docker 未安装或不在 PATH 中"
            ;;
        containerd)
            command -v ctr >/dev/null 2>&1 || die "ctr 未安装或不在 PATH 中"
            ;;
        *)
            die "RUNTIME 只支持 docker 或 containerd，当前为: $RUNTIME"
            ;;
    esac
}

pull_with_accelerator_docker() {
    local orig_image="$1"
    local accel_image="${SPEEDSERVER}/${orig_image}"

    log "docker pull 加速镜像: ${accel_image}"
    docker image pull "${accel_image}"

    # 给镜像打回原 tag
    log "docker tag ${accel_image} -> ${orig_image}"
    docker image tag "${accel_image}" "${orig_image}"

    # 删除加速镜像
    log "docker rmi ${accel_image}"
    docker image rmi "${accel_image}" || log "docker rmi ${accel_image} 失败（可能已被使用），忽略"
}

pull_with_accelerator_containerd() {
    local orig_image="$1"
    local accel_image="${SPEEDSERVER}/${orig_image}"

    log "ctr pull 加速镜像: ${accel_image}"
    ctr -n "${CONTAINERD_NS}" images pull "${accel_image}"

    # 给镜像打回原 tag
    log "ctr tag ${accel_image} -> ${orig_image}"
    ctr -n "${CONTAINERD_NS}" images tag "${accel_image}" "${orig_image}"

    # 删除加速镜像
    log "ctr rmi ${accel_image}"
    ctr -n "${CONTAINERD_NS}" images rm "${accel_image}" || log "ctr images rm ${accel_image} 失败（可能被容器使用），忽略"
}

process_image() {
    local image="$1"

    # 清理首尾空白
    image="$(echo "$image" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
    # 空行或注释行跳过
    [[ -z "$image" ]] && return
    [[ "$image" =~ ^# ]] && return

    log "处理镜像: ${image}"

    case "$RUNTIME" in
        docker)
            pull_with_accelerator_docker "${image}"
            ;;
        containerd)
            pull_with_accelerator_containerd "${image}"
            ;;
    esac

    log "完成镜像: ${image}"
}

main() {
    [[ -f "$IMAGES_LIST" ]] || die "镜像列表文件不存在: ${IMAGES_LIST}"

    check_runtime

    log "使用运行时: ${RUNTIME}"
    log "使用加速器: ${SPEEDSERVER}"
    log "镜像列表:   ${IMAGES_LIST}"

    while IFS= read -r line; do
        process_image "$line"
    done < "$IMAGES_LIST"

    log "全部镜像处理完成"
}

main "$@"
