#!/bin/bash

# 镜像保存脚本
# 用于保存 Docker 镜像到 tar 文件，便于离线部署

set -e

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

echo "=========================================="
echo "  Docker 镜像保存脚本"
echo "=========================================="
echo ""
echo "输出目录: $OUTPUT_DIR"
echo ""

# 创建输出目录
mkdir -p "$OUTPUT_DIR"

# 定义镜像名称（与 docker-compose.yml 保持一致）
declare -A IMAGES=(
    ["argus-metric-ftp:latest"]="argus-ftp.tar"
    ["argus-metric-prometheus:latest"]="argus-prometheus.tar"
    ["argus-metric-grafana:latest"]="argus-grafana.tar"
    ["argus-metric-test-node:latest"]="argus-test-node.tar"
    ["argus-metric-test-gpu-node:latest"]="argus-test-gpu-node.tar"
)

# 检查镜像是否存在并保存
total=0
success=0
failed=0

for image in "${!IMAGES[@]}"; do
    total=$((total + 1))
    output_file="${OUTPUT_DIR}/${IMAGES[$image]}"
    
    echo "[$total] 检查镜像: $image"
    
    if docker images --format "{{.Repository}}:{{.Tag}}" | grep -q "^${image}$"; then
        echo "    ✓ 镜像存在，开始保存..."
        if docker save -o "$output_file" "$image"; then
            file_size=$(ls -lh "$output_file" | awk '{print $5}')
            echo "    ✓ 保存成功: ${IMAGES[$image]} ($file_size)"
            success=$((success + 1))
        else
            echo "    ✗ 保存失败: $image"
            failed=$((failed + 1))
        fi
    else
        echo "    ✗ 镜像不存在，请先构建镜像"
        failed=$((failed + 1))
    fi
    echo ""
done

echo "=========================================="
echo "  保存完成"
echo "=========================================="
echo ""
echo "统计："
echo "  总计: $total"
echo "  成功: $success"
echo "  失败: $failed"
echo ""
echo "输出目录: $OUTPUT_DIR"
echo ""

if [ $success -gt 0 ]; then
    echo "已保存的文件："
    ls -lh "$OUTPUT_DIR"/*.tar 2>/dev/null || true
    echo ""
    echo "文件列表："
    for image in "${!IMAGES[@]}"; do
        output_file="${OUTPUT_DIR}/${IMAGES[$image]}"
        if [ -f "$output_file" ]; then
            file_size=$(ls -lh "$output_file" | awk '{print $5}')
            echo "  - ${IMAGES[$image]} ($file_size)"
        fi
    done
fi

echo ""
echo "使用说明："
echo "1. 将 images-cache 目录复制到目标服务器的 ~/argus/src/metric/tests/ 下"
echo "2. 在目标服务器运行: bash scripts/common/start-all.sh"
echo ""

if [ $failed -gt 0 ]; then
    exit 1
fi

