#!/bin/bash

# 镜像加载脚本
# 用于从 tar 文件加载 Docker 镜像

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
INPUT_DIR="${1:-$TEST_DIR/images-cache}"

echo "=========================================="
echo "  Docker 镜像加载脚本"
echo "=========================================="
echo ""
echo "输入目录: $INPUT_DIR"
echo ""

# 检查输入目录是否存在
if [ ! -d "$INPUT_DIR" ]; then
    echo "错误: 目录不存在: $INPUT_DIR"
    exit 1
fi

# 查找所有tar文件并加载
total=0
success=0
failed=0

# 查找目录下所有.tar文件
tar_files=($(find "$INPUT_DIR" -name "*.tar" -type f 2>/dev/null | sort))

if [ ${#tar_files[@]} -eq 0 ]; then
    echo "错误: 在目录 $INPUT_DIR 中未找到任何 .tar 文件"
    exit 1
fi

echo "找到 ${#tar_files[@]} 个镜像文件："
for tar_file in "${tar_files[@]}"; do
    echo "  - $(basename "$tar_file")"
done
echo ""

for tar_file in "${tar_files[@]}"; do
    total=$((total + 1))
    tar_filename=$(basename "$tar_file")
    
    echo "[$total] 处理: $tar_filename"
    
    # 强制加载，不检查镜像是否已存在
    echo "    加载镜像..."
    if docker load -i "$tar_file"; then
        echo "    加载成功: $tar_filename"
        success=$((success + 1))
    else
        echo "    加载失败: $tar_filename"
        failed=$((failed + 1))
    fi
    echo ""
done

echo "=========================================="
echo "  加载完成"
echo "=========================================="
echo ""
echo "统计："
echo "  总计: $total"
echo "  成功: $success"
echo "  失败: $failed"
echo ""

# 显示当前所有镜像
echo "当前所有镜像："
docker images
echo ""

if [ $failed -gt 0 ]; then
    echo "部分镜像加载失败，请检查！"
    exit 1
fi

if [ $success -gt 0 ]; then
    echo "镜像加载成功！"
fi

