#!/usr/bin/env bash
# 文件名: import_images.sh
# 功  能: 导入镜像
# 作  者: 邱树辉<qiushuhui@oschina.cn>

set -o pipefail

txtbld=$(tput bold)             # Bold
bldred=${txtbld}$(tput setaf 1) # red
bldgre=${txtbld}$(tput setaf 2) # green
bldylw=${txtbld}$(tput setaf 3) # yellow
txtrst=$(tput sgr0)             # Reset
err=${bldred}ERROR${txtrst}
info=${bldgre}INFO${txtrst}
warn=${bldylw}WARNING${txtrst}

imgSuccessful=0
imgFailed=0

image_path=${1:-./}

registry=hub.gitee.local:5000
repository=base-platform

for image_file in $(ls ${image_path} | egrep ".tar$" | sed 's/.tar//')
do
    image=$(echo ${image_file##*/} | sed 's/@/:/')

    printf "$info: [ ${bldylw}${image##*/}${txtrst} ] 镜像开始导入"

    skopeo copy docker-archive:${image_path}/${image_file}.tar docker://${registry}/${repository}/${image} >/dev/null 2>/dev/null || \
    skopeo copy --insecure-policy --dest-tls-verify=false docker-archive:${image_path}/${image_file}.tar docker://${registry}/${repository}/${image} >/dev/null 2>/dev/null

    if [[ "$?" -eq "0" ]]; then
        printf " | ${bldgre}√${txtrst}\n"
        let imgSuccessful=${imgSuccessful}+1
    else
        printf " | ${bldred}×${txtrst}\n"
        let imgFailed=${imgFailed}+1
    fi
done
printf "$info: 导入成功镜像数量: [ ${bldgre}${imgSuccessful}${txtrst} ]\n"

if [[ "${imgFailed}" != "0" ]]
then
    printf "$err: 导入失败镜像数量: [ ${bldred}${imgFailed}${txtrst} ]\n"
fi
