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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
MODULE_ROOT="$(cd "$TEST_ROOT/.." && pwd)"
PRIVATE_ROOT="$TEST_ROOT/private"
TMP_ROOT="$TEST_ROOT/tmp"
DNS_ROOT="$PRIVATE_ROOT/argus/etc"
BIND_UPDATE_SCRIPT_SRC="$(cd "$MODULE_ROOT/../bind" && pwd)/build/update-dns.sh"
BIND_UPDATE_SCRIPT_DEST="$DNS_ROOT/update-dns.sh"

mkdir -p "$PRIVATE_ROOT/argus/master"
mkdir -p "$PRIVATE_ROOT/argus/metric/prometheus"
mkdir -p "$TMP_ROOT"
mkdir -p "$DNS_ROOT"

# 确保上一次运行留下的容器/数据被清理
compose() {
  if docker compose version >/dev/null 2>&1; then
    docker compose "$@"
  else
    docker-compose "$@"
  fi
}

pushd "$TEST_ROOT" >/dev/null
compose down --remove-orphans || true
popd >/dev/null

rm -rf "$TMP_ROOT" "$PRIVATE_ROOT"
mkdir -p "$PRIVATE_ROOT/argus/master"
mkdir -p "$PRIVATE_ROOT/argus/metric/prometheus"
mkdir -p "$TMP_ROOT"
mkdir -p "$DNS_ROOT"

# 中文提示：将 bind 模块自带的 update-dns.sh 下发到共享目录，模拟实际环境
if [[ -f "$BIND_UPDATE_SCRIPT_SRC" ]]; then
  cp "$BIND_UPDATE_SCRIPT_SRC" "$BIND_UPDATE_SCRIPT_DEST"
  chmod +x "$BIND_UPDATE_SCRIPT_DEST"
else
  echo "[WARN] bind update script missing at $BIND_UPDATE_SCRIPT_SRC"
fi

pushd "$TEST_ROOT" >/dev/null
compose down --remove-orphans || true
MASTER_IMAGE_TAG="${MASTER_IMAGE_TAG:-argus-master:dev}" compose up -d
popd >/dev/null

echo "[INFO] Master container is up on http://localhost:31300"
