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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
AGENT_ROOT="$(cd "$TEST_ROOT/.." && pwd)"
MASTER_ROOT="$(cd "$AGENT_ROOT/../master" && pwd)"
REPO_ROOT="$(cd "$AGENT_ROOT/../.." && pwd)"
PRIVATE_ROOT="$TEST_ROOT/private"
TMP_ROOT="$TEST_ROOT/tmp"

AGENT_HOSTNAME="dev-e2euser-e2einst-pod-0"
AGENT_CONFIG_DIR="$PRIVATE_ROOT/argus/agent/$AGENT_HOSTNAME"
AGENT_HEALTH_DIR="$PRIVATE_ROOT/argus/agent/$AGENT_HOSTNAME/health"
MASTER_PRIVATE_DIR="$PRIVATE_ROOT/argus/master"
METRIC_PRIVATE_DIR="$PRIVATE_ROOT/argus/metric/prometheus"
DNS_DIR="$PRIVATE_ROOT/argus/etc"
BIND_IMAGE_TAG="${BIND_IMAGE_TAG:-argus-bind9:e2e}"
BIND_ROOT="$(cd "$MASTER_ROOT/../bind" && pwd)"

mkdir -p "$AGENT_CONFIG_DIR"
mkdir -p "$AGENT_HEALTH_DIR"
mkdir -p "$MASTER_PRIVATE_DIR"
mkdir -p "$METRIC_PRIVATE_DIR"
mkdir -p "$TMP_ROOT"
mkdir -p "$DNS_DIR"

touch "$AGENT_HEALTH_DIR/.keep"

# 中文提示：准备 bind 模块提供的 update-dns.sh，模拟生产下发
if [[ -f "$BIND_ROOT/build/update-dns.sh" ]]; then
  cp "$BIND_ROOT/build/update-dns.sh" "$DNS_DIR/update-dns.sh"
  chmod +x "$DNS_DIR/update-dns.sh"
else
  echo "[WARN] bind update script missing at $BIND_ROOT/build/update-dns.sh"
fi

pushd "$MASTER_ROOT" >/dev/null
./scripts/build_images.sh --tag argus-master:dev
popd >/dev/null

AGENT_BINARY="$AGENT_ROOT/dist/argus-agent"

pushd "$AGENT_ROOT" >/dev/null
./scripts/build_binary.sh
popd >/dev/null

if [[ ! -x "$AGENT_BINARY" ]]; then
  echo "[ERROR] Agent binary not found at $AGENT_BINARY" >&2
  exit 1
fi

# 中文提示：构建测试专用 bind9 镜像，确保解析服务可用
pushd "$REPO_ROOT" >/dev/null
docker build -f src/bind/build/Dockerfile -t "$BIND_IMAGE_TAG" .
popd >/dev/null

echo "$AGENT_BINARY" > "$TMP_ROOT/agent_binary_path"
echo "$BIND_IMAGE_TAG" > "$TMP_ROOT/bind_image_tag"

echo "[INFO] Agent E2E bootstrap complete"
