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

home="${DOBOTAI_HOME:-/opt/dobotai}"
container_dir="$home/container"
compose_file="$container_dir/compose.yaml"
runtime_env="$container_dir/runtime.env"
health_url="http://127.0.0.1:8090/healthz"

if [[ ! -r "$compose_file" || ! -r "$runtime_env" ]]; then
  echo "Docker 运行文件未安装。请先执行 install-docker.sh。" >&2
  exit 1
fi

compose=(docker compose --env-file "$runtime_env" -f "$compose_file")
previous_image="$(docker inspect --format '{{.Config.Image}}' dobotai-dingtalk 2>/dev/null || true)"

set_runtime_image() {
  local image="$1"
  python3 - "$runtime_env" "$image" <<'PY'
from pathlib import Path
import os
import sys
path = Path(sys.argv[1])
image = sys.argv[2]
lines = path.read_text(encoding="utf-8").splitlines()
rendered = ["DOBOTAI_IMAGE=" + image if line.startswith("DOBOTAI_IMAGE=") else line for line in lines]
if not any(line.startswith("DOBOTAI_IMAGE=") for line in lines):
    rendered.append("DOBOTAI_IMAGE=" + image)
temporary = path.with_name(path.name + ".new")
temporary.write_text("\n".join(rendered) + "\n", encoding="utf-8")
os.chmod(temporary, 0o600)
os.replace(temporary, path)
PY
}

rollback() {
  "${compose[@]}" rm -sf dobotai-dingtalk >/dev/null 2>&1 || true
  if [[ -n "$previous_image" ]]; then
    set_runtime_image "$previous_image"
    "${compose[@]}" up -d --no-build --force-recreate dobotai-dingtalk >/dev/null 2>&1 || true
  fi
}
trap rollback ERR

"${compose[@]}" up -d --no-build dobotai-postgres
"${compose[@]}" up -d --no-build --force-recreate dobotai-dingtalk
for _ in $(seq 1 30); do
  if curl --noproxy '*' --fail --silent --max-time 2 "$health_url" >/dev/null; then
    trap - ERR
    echo "DobotAI 容器已启动：dobotai-dingtalk"
    exit 0
  fi
  sleep 1
done

echo "DobotAI 容器健康检查失败，已回滚到上一容器镜像（如存在）。" >&2
exit 1
