#!/usr/bin/env bash

set -euo pipefail

# ============================================================
# 配置区：修改以下变量
# ============================================================
REGISTRY="chongqingshcis-a189ec98.ecis.chongqing-1.cmecloud.cn"            # 登录地址 / 目标仓库域名
NAMESPACE="cmii"              # 目标命名空间
USERNAME="cqcmii"      # 仓库登录用户名
PASSWORD='pL8$kq9@m'     # 仓库登录密码
INPUT_FILE="middleware-fly-amd64-260311.txt"       # 镜像列表文件路径
# ============================================================

# 登录到私有仓库
echo ">>> Logging in to $REGISTRY..."
echo "$PASSWORD" | docker login "$REGISTRY" -u "$USERNAME" --password-stdin

# 逐行处理镜像
while IFS= read -r line || [ -n "$line" ]; do
    # 跳过空行和注释行
    [[ -z "$line" || "$line" == \#* ]] && continue

    # 拆分 repo 和 tag
    if [[ "$line" =~ (.*):(.*) ]]; then
        repo="${BASH_REMATCH[1]}"
        tag="${BASH_REMATCH[2]}"
    else
        repo="$line"
        tag="latest"
    fi

    # 只保留镜像名最后一段（去掉原有 namespace/domain）
    image_name="${repo##*/}"

    src_image="${repo}:${tag}"
    dest_image="${REGISTRY}/${NAMESPACE}/${image_name}:${tag}"

    echo ""
    echo ">>> [pull ] $src_image"
    docker pull "$src_image"

    echo ">>> [tag  ] $src_image  →  $dest_image"
    docker tag "$src_image" "$dest_image"

    echo ">>> [push ] $dest_image"
    docker push "$dest_image"

done < "$INPUT_FILE"

echo ""
echo ">>> All done."
