#!/bin/bash

set -e  # 构建失败就退出

IMAGE_NAME="cradle:latest"
CONTAINER_NAME="Cradle"

echo "🔍 检查旧容器是否存在..."
if docker ps -a --format '{{.Names}}' | grep -Eq "^${CONTAINER_NAME}\$"; then
  echo "🛑 停止旧容器: $CONTAINER_NAME"
  docker stop "$CONTAINER_NAME"
  echo "❌ 删除旧容器: $CONTAINER_NAME"
  docker rm "$CONTAINER_NAME"
fi

echo "🧹 删除旧镜像（如果存在）..."
if docker images --format '{{.Repository}}:{{.Tag}}' | grep -Eq "^cradle:latest\$"; then
  docker rmi -f "$IMAGE_NAME"
fi

echo "⬇️ 拉取最新代码..."
git pull

echo "🧼 清除 .next..."
rm -rf apps/blogai/.next

echo "📦 构建镜像..."
if ! docker build \
  --build-arg http_proxy=http://127.0.0.1:7890 \
  --build-arg https_proxy=http://127.0.0.1:7890 \
  --build-arg BLOGAI_HOST=ai.szaiai.com \
  --no-cache \
  --network=host \
  -t cradle:latest \
  -f apps/blogai/Dockerfile .; then
  echo "❌ 构建失败，退出"
  exit 1
fi

echo "🚀 启动新容器..."
docker run -d --name Cradle -p 3008:3008 --restart always -e SUPABASE_URL="http://183.36.35.42:80" cradle:latest

