#!/bin/bash

# ETF策略 - 构建和推送脚本
# 使用 docker 构建镜像并推送到私有仓库

set -e  # 遇到错误立即退出

# 配置变量
IMAGE_NAME="${1:-etf-scheduler}"
REGISTRY="192.168.0.115:5000"
TAG="latest"
FULL_IMAGE_NAME="${REGISTRY}/${IMAGE_NAME}:${TAG}"

echo "========================================="
echo "ETF策略 构建和推送脚本"
echo "========================================="
echo "镜像名称: ${IMAGE_NAME}"
echo ""

# 检查并构建基础镜像（如果不存在）
echo "0. 检查基础镜像..."
if ! docker images --format "{{.Repository}}:{{.Tag}}" | grep -q "index-base:latest"; then
    echo "   基础镜像不存在，开始构建..."
    if [ -f "Dockerfile_base" ]; then
        docker build --platform linux/arm64 -f Dockerfile_base -t index-base:latest .
        echo "   ✅ 基础镜像构建成功"
    else
        echo "   ⚠️ 未找到 Dockerfile_base，跳过基础镜像构建"
        exit 1
    fi
else
    echo "   ✅ 基础镜像已存在"
fi

# 构建镜像
echo "1. 构建 Docker 镜像..."
echo "   镜像名称: ${IMAGE_NAME}"
docker build --platform linux/arm64 -t ${IMAGE_NAME} .

if [ $? -eq 0 ]; then
    echo "   ✅ 镜像构建成功"
else
    echo "   ❌ 镜像构建失败"
    exit 1
fi

# 打标签
echo "2. 为镜像打标签..."
echo "   标签: ${FULL_IMAGE_NAME}"
docker tag ${IMAGE_NAME} ${FULL_IMAGE_NAME}

if [ $? -eq 0 ]; then
    echo "   ✅ 标签添加成功"
else
    echo "   ❌ 标签添加失败"
    exit 1
fi

# 推送到私有仓库
echo "3. 推送镜像到私有仓库..."
echo "   仓库地址: ${REGISTRY}"
docker push ${FULL_IMAGE_NAME}

if [ $? -eq 0 ]; then
    echo "   ✅ 镜像推送成功"
else
    echo "   ❌ 镜像推送失败"
    exit 1
fi

# 清理本地镜像（可选）
echo "4. 清理临时镜像..."
docker rmi ${IMAGE_NAME} || true

# 显示最终结果
echo ""
echo "========================================="
echo "🎉 构建和推送完成！"
echo "========================================="
echo "镜像地址: ${FULL_IMAGE_NAME}"
echo ""
echo "可以使用以下命令运行容器："
echo "docker run -d --name etf-scheduler-container \"
echo "  -v /path/to/.env:/app/.env \"
echo "  -v /path/to/hk_ecs.pem:/app/hk_ecs.pem \"
echo "  -v /path/to/data:/app/data \"
echo "  ${FULL_IMAGE_NAME}"
echo ""
echo "或者在其他机器上拉取镜像："
echo "docker pull k3d-quant-registry:5000/${IMAGE_NAME}:${TAG}"
echo "========================================="