#!/bin/bash
# 用法: ./update-image.sh [目录1] [目录2] ... <new-tag>
# 示例: ./update-image.sh /opt/ov /opt/cn 202604071354-feat-region-sync-glm
#
# 脚本会修改指定目录下 docker-compose.yml 中 new-api 服务的 image tag。
# 如果不传目录参数，默认修改当前目录。

set -e

if [ $# -lt 1 ]; then
  echo "错误: 请提供新的 tag"
  echo "用法: $0 [目录1] [目录2] ... <new-tag>"
  echo "示例: $0 /opt/ov /opt/cn 202604071354-feat-region-sync-glm"
  exit 1
fi

TAG="${@: -1}"

if [ $# -gt 1 ]; then
  DIRS=("${@:1:$#-1}")
else
  DIRS=(".")
fi

update_file() {
  local FILE="$1"
  local TAG="$2"

  if [ ! -f "$FILE" ]; then
    echo "跳过: $FILE 不存在"
    return
  fi

  OLD_IMAGE=$(grep -E '^\s+image:.*new-api' "$FILE" | head -1 | sed 's/.*image: *//')
  OLD_TAG="${OLD_IMAGE##*:}"
  REPO="${OLD_IMAGE%:*}"

  if [ -z "$OLD_TAG" ] || [ -z "$REPO" ]; then
    echo "错误: 无法从 $FILE 中解析 new-api 的 image 配置"
    return 1
  fi

  NEW_IMAGE="${REPO}:${TAG}"

  if [[ "$OSTYPE" == "darwin"* ]]; then
    perl -i -pe "s|(\s+image:) *${OLD_IMAGE}|\$1 ${NEW_IMAGE}|" "$FILE"
  else
    sed -i "s|${OLD_IMAGE}|${NEW_IMAGE}|" "$FILE"
  fi

  echo "已更新 $FILE:"
  echo "  旧: ${OLD_IMAGE}"
  echo "  新: ${NEW_IMAGE}"
}

for DIR in "${DIRS[@]}"; do
  FILE="${DIR%/}/docker-compose.yml"
  update_file "$FILE" "$TAG"
done
