#!/bin/bash

# 约定内容
OSS_URL=https://oss.demo.uavcmlc.com:18000/cmlc-installation/tmp/
NeedUploadFolder=0
IsUpload=0
UploadImageName=""
ImageTarName=""
InnerIPv4CIDR=""
InnerIPv6CIDR=""
InnerIPv4=""
InnerIPv6=""
CmiiImagePrefix="harbor.cdcyy.com.cn/cmii/"

get_image_tar_name() {

  # harbor.cdcyy.com.cn/cmii/cmii-uav-oauth:4.1.6
  local imageName=$(echo $UploadImageName | cut -d ":" -f1 | cut -d"/" -f3)
  local imageTag=$(echo $UploadImageName | cut -d ":" -f2)
  local currentDate=$(date -d "2023-09-18" +%Y%m%d)
  local random_number=$((RANDOM%900 + 100))

  ImageTarName="$imageName=$imageTag=$currentDate=$random_number.tar.gz"
}

get_image_name_from_tar(){

  # cmii-uav-oauth_4.1.6-0918_20230918_123.tar.gz

  local image_name=$(echo $ImageTarName | cut -d "=" -f1)
  local tag_name=$(echo $ImageTarName | cut -d"=" -f2)


  UploadImageName="$image_name:$tag_name"
}

# 获取服务器的公网IP地址
get_Internal_IP_CIDR() {

  local interface_prefix=("[[:space:]]eth[0-9]{1,2}" "[[:space:]]ens[0-9]{1,3}" "[[:space:]]eno[0-9]{1,3}" "[[:space:]]enp[0-9]{1,2}")
  local real_interface="eth90"

  for interface in "${interface_prefix[@]}"; do
      echo $(ip link show) | grep -oE ${interface} | head -1
      if [[ $? -eq 0 ]]; then
          real_interface=$(echo $(ip link show) | grep -oE ${interface} | head -1 | cut -d" " -f2)
          echo "当前主机的真实内网网卡为 => [$real_interface]"
          break
    fi
  done

  # 提取IPv4地址（CIDR格式）
  local ipv4_regex="inet[[:space:]](25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/[0-9]{1,2}"

  # 提取IPv6地址（CIDR格式）
  local ipv6_regex="inet6[[:space:]]([0-9a-fA-F]{0,4}(:[0-9a-fA-F]{0,4}){1,7})\/[0-9]{1,3}"

  # 查找IPv4地址
  local inner_ipv4=$(echo $(ip addr show $real_interface) | grep -oE $ipv4_regex | cut -d" " -f2)
  InnerIPv4CIDR=$inner_ipv4
  echo "Interface: $real_interface, IPv4 Address: $inner_ipv4"

   # 查找IPv6地址
  local inner_ipv6=$(echo $(ip addr show $real_interface) | grep -oE $ipv6_regex | cut -d" " -f2)
  InnerIPv6CIDR=$inner_ipv6
  echo "Interface: $real_interface, IPv4 Address: $inner_ipv6"

}

get_Internal_IP() {

  get_Internal_IP_CIDR

  InnerIPv4=$(echo $InnerIPv4CIDR | cut -d "/" -f1)
  InnerIPv6=$(echo $InnerIPv6CIDR | cut -d "/" -f1)

  echo "服务器的内网IPv4地址为 $InnerIPv4"
  echo "服务器的内网IPv6地址为 $InnerIPv6"

}

_math() {
  _m_opts="$@"
  printf "%s" "$(($_m_opts))"
}

# 前文内容

while [[ $# > 0 ]]; do
    case "$1" in
        -f | --file)
        NeedUploadFolder=1
        shift # past argument
        ;;
        -u | --upload)
        IsUpload=1
        UploadImageName="${2}"
        shift # past argument
        ;;
        -d | --download)
        IsUpload=0
        ImageTarName="${2}"
        shift # past argument
        ;;
        *)
                # unknown option
        ;;
  esac
    shift # past argument or value
done

if [[ $NeedUploadFolder == 1 ]]; then
    # 上传的是一个目录

fi


if [[ $IsUpload == 1 ]]; then
    # upload
    echo "【上传】 - 需要处理的镜像名称为 => $UploadImageName"
    echo ""
    echo "【上传】 - 开始下载镜像！"
    echo ""
    if docker pull "${UploadImageName}" >/dev/null 2>&1; then
        echo "下载-镜像下载成功！ => $UploadImageName"
  else
      if docker inspect "${UploadImageName}" >/dev/null 2>&1; then
        echo "下载-镜像已经存在 => $UploadImageName"
    else
        echo "下载-镜像下载失败！ => $UploadImageName"
    fi
  fi
    echo ""

    get_image_tar_name
    echo "【上传】 - 将要把镜像压缩为 => $ImageTarName"
    docker save $UploadImageName | gzip --stdout >${ImageTarName}
    echo "【上传】 - 压缩成功 ！ $(ls | grep ${ImageTarName})"
    echo""

    echo "【上传】 - 开始上传至OSS中!"
    mc cp ./${ImageTarName} demo/cmlc-installation/tmp/
    echo "【上传】 - 上传OSS成功 => $(mc ls demo/cmlc-installation/tmp/ | grep ${ImageTarName})"
    echo""

    echo "【上传】 - 请在目标Master主机执行如下命令 ↓↓↓↓↓↓"
    echo ""
    echo ""
    echo "source <(curl -sL https://b2.107421.xyz/image-sync.sh) -d $ImageTarName"
    echo ""
    echo ""
else
    # download
    echo "【下载】 - 需要处理的压缩包名称为 => $ImageTarName"

    echo "【下载】 - 开始下载 ↓"
    wget "$OSS_URL$ImageTarName"
    if [[ $? -ne 0 ]]; then
        echo "【下载】- 下载镜像失败！退出！"
        return
    fi
    echo ""

    echo "【下载】 - 开始解压压缩包 "
    docker load < "${ImageTarName}"
    echo ""

    get_Internal_IP
    echo "【下载】 - 开始上传镜像到本地的镜像仓库中 => $InnerIPv4:8033 "
    custom_prefix="$InnerIPv4:8033/cmii/"
    echo ""

    get_image_name_from_tar
    echo "【下载】 - 解析得到的 私有镜像地址为 => $custom_prefix$UploadImageName"
    docker tag "$CmiiImagePrefix${UploadImageName}" "$custom_prefix$UploadImageName"

    echo "【下载】 - 开始上传镜像到私有仓库 ↓"
    docker login -u admin -p V2ryStr@ngPss "$InnerIPv4:8033"
    echo ""
    echo "【下载】 - 开始推送到私有仓库！ "
    docker push "$custom_prefix$UploadImageName"
    echo ""
    echo ""

    echo "【下载】 - 请等待流程结束 ↓"
    _sleep_c="500"
    while [ "$_sleep_c" -ge "0" ]; do
      printf "\r      \r"
       printf -- "%b" "$_sleep_c"
      _sleep_c="$(_math "$_sleep_c" - 1)"
      sleep 1
    done
    printf "\r"
fi

