#!/usr/bin/env bash

# 判断环境平台
if [ -z "${ARCH}" ]; then
  case $(uname -m) in
    x86_64) ARCH=amd64 ;;
    aarch64) ARCH=arm64 ;;
    *) printf "$err: 不支持该平台 $(uname -m)"; exit 1 ;;
  esac
fi

package_name="longhorn-1.3.3-images.${ARCH}.tar.xz"
image_path="longhorn"

# 终端颜色定义
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}

k8s_images=(
    registry.cn-shenzhen.aliyuncs.com/shuhui/longhorn-manager:v1.3.3
    registry.cn-shenzhen.aliyuncs.com/shuhui/longhorn-ui:v1.3.3
    registry.cn-shenzhen.aliyuncs.com/shuhui/longhorn-engine:v1.3.3
    registry.cn-shenzhen.aliyuncs.com/shuhui/longhorn-instance-manager:v1_20230407
    registry.cn-shenzhen.aliyuncs.com/shuhui/longhorn-share-manager:v1_20230320
    registry.cn-shenzhen.aliyuncs.com/shuhui/backing-image-manager:v3_20230320
    registry.cn-shenzhen.aliyuncs.com/shuhui/csi-attacher:v3.4.0
    registry.cn-shenzhen.aliyuncs.com/shuhui/csi-provisioner:v2.1.2
    registry.cn-shenzhen.aliyuncs.com/shuhui/csi-node-driver-registrar:v2.5.0
    registry.cn-shenzhen.aliyuncs.com/shuhui/csi-resizer:v1.2.0
    registry.cn-shenzhen.aliyuncs.com/shuhui/csi-snapshotter:v3.0.3
    registry.cn-shenzhen.aliyuncs.com/shuhui/livenessprobe:v2.8.0
)

imgSuccessful=0
imgFailed=0

install -d ${image_path}
for img in ${k8s_images[@]}
do

    if [[ ! -e $(realpath .)/${image_path}/$(echo ${img##*/} | awk -F ":" '{print $1}').tar ]]
    then
        printf "$info: 镜像导出 [ ${bldgre}${img}${txtrst} ]"
        skopeo copy docker://${img} docker-archive:$(realpath .)/${image_path}/$(echo ${img##*/} | awk -F ":" '{print $1}').tar  >/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
    else
        printf "$info: 镜像存在 [ ${bldgre}${img}${txtrst} ]\n"
    fi
done

cd $(realpath .)/${image_path}/ && XZ_OPT='-T0 -9' tar -cvJf ${package_name} *.tar  --remove-files
