#!/bin/bash

# 构建并推送 nginx 镜像到私有仓库
# 使用方法: 在 docker/nginx 目录下执行 ./build-and-push-nginx.sh

set -e

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# 项目根目录（脚本所在目录的上两级）
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"

# 配置变量
REGISTRY="registry.t-aaron.com"
IMAGE_NAME="polaris-nginx"
VERSION="latest"
PLATFORM="linux/amd64"
DOCKERFILE="Dockerfile.registry"

# 完整镜像名称
FULL_IMAGE_NAME="${REGISTRY}/${IMAGE_NAME}:${VERSION}"

echo "=========================================="
echo "开始构建 Nginx 镜像"
echo "=========================================="
echo "脚本目录: ${SCRIPT_DIR}"
echo "项目根目录: ${PROJECT_ROOT}"
echo "镜像名称: ${FULL_IMAGE_NAME}"
echo "平台架构: ${PLATFORM}"
echo "Dockerfile: ${SCRIPT_DIR}/${DOCKERFILE}"
echo "=========================================="

# 检查 Dockerfile 是否存在
if [ ! -f "${SCRIPT_DIR}/${DOCKERFILE}" ]; then
    echo "错误: 未找到 Dockerfile: ${SCRIPT_DIR}/${DOCKERFILE}"
    exit 1
fi

# 检查 buildx 是否可用
if ! docker buildx version &> /dev/null; then
    echo "错误: docker buildx 不可用"
    echo "请先安装 docker buildx"
    exit 1
fi

# 切换到项目根目录作为构建上下文
cd "${PROJECT_ROOT}"

# 构建并推送镜像
echo ""
echo "开始构建镜像..."
docker buildx build \
  --platform ${PLATFORM} \
  -t ${FULL_IMAGE_NAME} \
  -f docker/nginx/${DOCKERFILE} \
  --push \
  .

echo ""
echo "=========================================="
echo "构建完成！"
echo "镜像已推送到: ${FULL_IMAGE_NAME}"
echo "=========================================="
