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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
REPO_ROOT="$(cd "$TEST_ROOT/../../.." && pwd)"

compose() {
  if docker compose version >/dev/null 2>&1; then
    docker compose "$@"
  else
    docker-compose "$@"
  fi
}

echo "[INFO] Bringing up system stack..."

REQUEST_GPU=${ARGUS_SYS_ENABLE_GPU:-false}
GPU_AVAILABLE=false
GPU_CHECK_SCRIPT="$REPO_ROOT/src/metric/tests/scripts/common/check-gpu.sh"

if [[ "$REQUEST_GPU" == "true" ]]; then
  echo "[INFO] --enable-gpu 生效，验证主机 GPU..."
  if [[ -f "$GPU_CHECK_SCRIPT" ]]; then
    if bash "$GPU_CHECK_SCRIPT" >/dev/null 2>&1; then
      GPU_AVAILABLE=true
      echo "[INFO] GPU 检测通过，将启动 gpu profile"
    else
      echo "[ERROR] 主机缺少可用 GPU，无法继续 --enable-gpu 流程" >&2
      exit 1
    fi
  else
    echo "[ERROR] 未找到 GPU 检测脚本: $GPU_CHECK_SCRIPT" >&2
    exit 1
  fi
else
  echo "[INFO] 未启用 GPU 流程"
fi

pushd "$TEST_ROOT" >/dev/null
compose -p argus-sys down --remove-orphans || true

# 清理可能由 08 脚本创建的同名容器，避免 compose up 冲突
for name in argus-node-b; do
  if docker ps -aqf "name=^${name}$" >/dev/null 2>&1 && [[ -n "$(docker ps -aqf "name=^${name}$")" ]]; then
    docker rm -f "$name" >/dev/null 2>&1 || true
  fi
done

# 根据GPU可用性决定启动的服务
if [[ "$GPU_AVAILABLE" == true ]]; then
  echo "[INFO] 启动所有服务（包含 gpu profile）..."
  compose -p argus-sys --profile gpu up -d
else
  echo "[INFO] 启动基础服务（不含 gpu profile）..."
  compose -p argus-sys up -d
fi

popd >/dev/null

if [[ "$GPU_AVAILABLE" == true ]]; then
  echo "[OK] Services started: master:32300 es:9200 kibana:5601 node-a:2020 node-b:2021 test-gpu-node:172.29.0.51"
else
  echo "[OK] Services started: master:32300 es:9200 kibana:5601 node-a:2020 node-b:2021 (gpu skipped)"
fi
