#!/usr/bin/env bash
set -euo pipefail

IMAGE_NAME="bge-m3-openai-api"
CONTAINER_NAME="bge-m3-openai-api"
HOST_PORT=8001
MODEL_DIR="$(pwd)/model/bge-m3"
FLAG_DIR="$(pwd)/FlagEmbedding"

echo "==> 1. 停止并删除旧容器"
containers=$(docker ps -a --filter "ancestor=${IMAGE_NAME}" -q)
if [ -n "$containers" ]; then
  echo "Stopping: $containers"
  docker stop $containers
  echo "Removing: $containers"
  docker rm   $containers
else
  echo "No existing containers for image ${IMAGE_NAME}"
fi

echo
echo "==> 2. 删除旧镜像"
image_ids=$(docker images -q "${IMAGE_NAME}")
if [ -n "$image_ids" ]; then
  echo "Removing image IDs: $image_ids"
  docker rmi -f $image_ids
else
  echo "No existing images named ${IMAGE_NAME}"
fi

echo
echo "==> 3. 更新 FlagEmbedding 源码（如果是 git 仓库）"
if [ -d "${FLAG_DIR}/.git" ]; then
  git -C "${FLAG_DIR}" pull
else
  echo "${FLAG_DIR} is not a git repo, skipping 'git pull'"
fi

echo
echo "==> 4. 构建新镜像"
docker build -t "${IMAGE_NAME}" .

echo
echo "==> 5. 启动新容器"
docker run -d \
  --name "${CONTAINER_NAME}" \
  -p "${HOST_PORT}:${HOST_PORT}" \
  -v "${MODEL_DIR}:/app/model/bge-m3" \
  "${IMAGE_NAME}"

echo
echo "✅ All done. Container '${CONTAINER_NAME}' is running on port ${HOST_PORT}."

