#!/bin/bash

set -e  # 出错即退出

IMAGE_NAME="plugai"
CONTAINER_NAME="minio"
DATA_DIR="/data/updsrv/cloud"

# 可选：配置构建代理（可注释掉或自定义）
export http_proxy="http://127.0.0.1:7890"
export https_proxy="http://127.0.0.1:7890"

echo "🧹 Step 1: 删除旧容器和镜像..."
docker rm -f $CONTAINER_NAME 2>/dev/null || true
docker rmi -f $IMAGE_NAME:latest 2>/dev/null || true

echo "🛠️ Step 2: 编译 minio 二进制..."
MINIO_RELEASE=on make

if [ ! -f ./minio ]; then
  echo "❌ 编译失败，未找到 minio 可执行文件"
  exit 1
fi

echo "🐳 Step 3: 构建 Docker 镜像..."
docker build --build-arg http_proxy=$http_proxy --build-arg https_proxy=$https_proxy -t $IMAGE_NAME:latest .

echo "🚀 Step 4: 运行新容器（使用端口映射）..."
docker run -d \
  --name $CONTAINER_NAME \
  --restart unless-stopped \
  -p 9000:9000 \
  -p 9001:9001 \
  -e MINIO_ROOT_USER=admin \
  -e MINIO_ROOT_PASSWORD=Admin@123.. \
  -e MINIO_BROWSER_REDIRECT_URL=https://console.szaiai.com \
  -v "$DATA_DIR":/data \
  $IMAGE_NAME:latest server /data --console-address "0.0.0.0:9001"

echo "✅ MinIO 已启动："
echo "📦 API 接口: http://localhost:9000"
echo "🖥️ 控制台: http://localhost:9001"
