#!/usr/bin/env bash
set -Eeuo pipefail

# =========================
# 基础配置
# =========================
OUTPUT_DIR="/var/lib/docker/wdd/octopus_image/cmii_uas_23_tmp"

IMAGES=(
  "bitnamilegacy/redis:6.2.14-debian-11-r19"
  "bitnamilegacy/redis:7.4.3-debian-12-r0"
  "bitnamilegacy/mysql:8.1.0-debian-11-r42"
  "bitnamilegacy/os-shell:12-debian-12-r51"
  "bitnamilegacy/rabbitmq:3.13.7-debian-12-r5"
  "ossrs/srs:v5.0.195"
  "emqx/emqx:5.8.8"
  "nacos/nacos-server:v2.1.2"
  "library/mongo:5.0"
  "minio/minio:RELEASE.2023-06-02T23-17-26Z"
  "nginx:1.28.2"
  "harbor.cdcyy.com.cn/cmii/doris.be-ubuntu:2.1.6"
  "harbor.cdcyy.com.cn/cmii/doris.fe-ubuntu:2.1.6"
)

# =========================
# 日志函数
# =========================
log() {
  local level="$1"
  shift
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*"
}

# =========================
# 异常处理
# =========================
on_error() {
  local exit_code=$?
  local line_no=${1:-unknown}
  log "ERROR" "脚本执行失败，行号: ${line_no}，退出码: ${exit_code}"
  exit "${exit_code}"
}
trap 'on_error $LINENO' ERR

# =========================
# 前置检查
# =========================
check_command() {
  local cmd="$1"
  if ! command -v "${cmd}" >/dev/null 2>&1; then
    log "ERROR" "缺少命令: ${cmd}"
    exit 1
  fi
}

check_command docker

mkdir -p "${OUTPUT_DIR}"
log "INFO" "输出目录已准备: ${OUTPUT_DIR}"

# =========================
# 工具函数
# =========================
image_exists() {
  local image="$1"
  docker image inspect "${image}" >/dev/null 2>&1
}

sanitize_filename() {
  local image="$1"
  # 将镜像名转换成适合文件名的格式
  # harbor.cdcyy.com.cn/cmii/cmii-uas-gateway:2.3.0-pro-20260226
  # ->
  # harbor.cdcyy.com.cn_cmii_cmii-uas-gateway_2.3.0-pro-20260226.tar
  local name
  name="${image//\//_}"
  name="${name//:/_}"
  echo "${name}.tar"
}

pull_image_if_needed() {
  local image="$1"
  if image_exists "${image}"; then
    log "INFO" "镜像已存在，无需拉取: ${image}"
  else
    log "INFO" "镜像不存在，开始拉取: ${image}"
    docker pull "${image}"
    log "INFO" "镜像拉取完成: ${image}"
  fi
}

save_image_to_tar() {
  local image="$1"
  local tar_name
  local tar_path

  tar_name="$(sanitize_filename "${image}")"
  tar_path="${OUTPUT_DIR}/${tar_name}"

  log "INFO" "开始打包镜像: ${image}"
  docker save -o "${tar_path}" "${image}"
  log "INFO" "镜像打包完成: ${tar_path}"
}

# =========================
# 主流程
# =========================
main() {
  local image

  for image in "${IMAGES[@]}"; do
    log "INFO" "----------------------------------------"
    log "INFO" "处理镜像: ${image}"

    pull_image_if_needed "${image}"
    save_image_to_tar "${image}"
  done

  log "INFO" "----------------------------------------"
  log "INFO" "全部镜像处理完成，输出目录: ${OUTPUT_DIR}"
}

main "$@"