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

container_dir="/opt/dobotai-test/container"
compose_file="$container_dir/compose.yaml"
runtime_env="$container_dir/runtime.env"
legacy_service="dobotai-test.service"
health_url="http://127.0.0.1:8090/healthz"

if [[ ! -r "$compose_file" || ! -r "$runtime_env" ]]; then
  echo "容器运行文件未安装。请先部署 dobotai-dingtalk。" >&2
  exit 1
fi

legacy_was_active=false
if systemctl is-active --quiet "$legacy_service"; then
  legacy_was_active=true
  systemctl stop "$legacy_service"
fi

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()
updated = False
rendered = []
for line in lines:
    if line.startswith("DOBOTAI_IMAGE="):
        rendered.append("DOBOTAI_IMAGE=" + image)
        updated = True
    else:
        rendered.append(line)
if not updated:
    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() {
  docker compose --env-file "$runtime_env" -f "$compose_file" down --remove-orphans >/dev/null 2>&1 || true
  if [[ -n "$previous_image" ]]; then
    set_runtime_image "$previous_image"
    docker compose --env-file "$runtime_env" -f "$compose_file" up -d --no-build --force-recreate >/dev/null 2>&1 || true
  elif [[ "$legacy_was_active" == "true" ]]; then
    systemctl start "$legacy_service" || true
  fi
}
trap rollback ERR

docker compose --env-file "$runtime_env" -f "$compose_file" up -d --no-build --force-recreate
for _ in $(seq 1 30); do
  if curl --noproxy '*' --fail --silent --max-time 2 "$health_url" >/dev/null; then
    systemctl disable "$legacy_service" >/dev/null
    trap - ERR
    echo "DobotAI 容器已启动：dobotai-dingtalk"
    exit 0
  fi
  sleep 1
done

if [[ -n "$previous_image" ]]; then
  echo "DobotAI 容器健康检查失败，已回滚到上一容器镜像。" >&2
else
  echo "DobotAI 容器健康检查失败，已回滚到原生服务。" >&2
fi
exit 1
