#!/usr/bin/env bash

set -euo pipefail

# ============================================================
# 配置区：修改以下变量
# ============================================================
REGISTRY="chongqingshcis-a189ec98.ecis.chongqing-1.cmecloud.cn"            # 登录地址 / 目标仓库域名
NAMESPACE="cmii"              # 目标命名空间
USERNAME="cqcmii"      # 仓库登录用户名
PASSWORD='pL8$kq9@m'     # 仓库登录密码
# ============================================================

# 参数校验
if [ $# -ne 1 ]; then
    echo "Usage: $0 <image>"
    echo "Example:"
    echo "  $0 nginx:latest"
    echo "  $0 harbor.cdcyy.com.cm/cmii/asdad:v1.2"
    echo "  $0 harbor.cdcyy.com.cm/cmii/cmii-live/asdad:v1.2"
    exit 1
fi

SRC_IMAGE="$1"

# ---------- 解析 image name 和 tag ----------
# 先分离 tag（冒号后面部分）
if [[ "$SRC_IMAGE" =~ ^(.*):([^:/]+)$ ]]; then
    repo="${BASH_REMATCH[1]}"
    tag="${BASH_REMATCH[2]}"
else
    repo="$SRC_IMAGE"
    tag="latest"
fi

# 只取路径最后一段作为镜像名（去掉任意层级 namespace/domain）
image_name="${repo##*/}"

DEST_IMAGE="${REGISTRY}/${NAMESPACE}/${image_name}:${tag}"
# --------------------------------------------

echo ">>> Source : $SRC_IMAGE"
echo ">>> Target : $DEST_IMAGE"
echo ""

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

# Pull
echo ">>> [pull ] $SRC_IMAGE"
docker pull "$SRC_IMAGE"

# Tag
echo ">>> [tag  ] $SRC_IMAGE  →  $DEST_IMAGE"
docker tag "$SRC_IMAGE" "$DEST_IMAGE"

# Push
echo ">>> [push ] $DEST_IMAGE"
docker push "$DEST_IMAGE"

echo ""
echo ">>> Done: $DEST_IMAGE"
