#!/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)"

PRIVATE_CORE="$TEST_ROOT/private"
PRIVATE_NODEA="$TEST_ROOT/private-nodea"
PRIVATE_NODEB="$TEST_ROOT/private-nodeb"
TMP_DIR="$TEST_ROOT/tmp"

source "$REPO_ROOT/scripts/common/build_user.sh"
load_build_user

ensure_image() {
  local image="$1"
  if ! docker image inspect "$image" >/dev/null 2>&1; then
    echo "[ERROR] Missing image: $image. Please run ./build/build_images.sh" >&2
    exit 1
  fi
}

echo "[INFO] Preparing directories..."
mkdir -p \
  "$PRIVATE_CORE/argus/etc" \
  "$PRIVATE_CORE/argus/bind" \
  "$PRIVATE_CORE/argus/master" \
  "$PRIVATE_CORE/argus/metric/prometheus" \
  "$PRIVATE_CORE/argus/log/elasticsearch" \
  "$PRIVATE_CORE/argus/log/kibana" \
  "$PRIVATE_NODEA/argus/agent/dev-yyrshare-nbnyx10-cp2f-pod-0/health" \
  "$PRIVATE_NODEB/argus/agent/dev-yyrshare-uuuu10-ep2f-pod-0/health" \
  "$TMP_DIR"

# Align ownership for supervisor-managed services (ES/Kibana expect UID/GID inside container)
echo "[INFO] Fixing ownership for core private directories..."
chown -R "${ARGUS_BUILD_UID}:${ARGUS_BUILD_GID}" \
  "$PRIVATE_CORE/argus/log/elasticsearch" \
  "$PRIVATE_CORE/argus/log/kibana" \
  "$PRIVATE_CORE/argus/etc" 2>/dev/null || true

echo "[INFO] Distributing update-dns.sh for core services (bind/master/es/kibana)"
BIND_UPDATE_SRC="$REPO_ROOT/src/bind/build/update-dns.sh"
BIND_UPDATE_DEST="$PRIVATE_CORE/argus/etc/update-dns.sh"
if [[ -f "$BIND_UPDATE_SRC" ]]; then
  cp "$BIND_UPDATE_SRC" "$BIND_UPDATE_DEST"
  chmod +x "$BIND_UPDATE_DEST"
else
  echo "[WARN] bind update-dns.sh not found at $BIND_UPDATE_SRC"
fi

echo "[INFO] Ensuring images present..."
ensure_image "argus-elasticsearch:latest"
ensure_image "argus-kibana:latest"
ensure_image "argus-bind9:latest"
ensure_image "argus-master:latest"

echo "[INFO] Building agent binary..."
pushd "$REPO_ROOT/src/agent" >/dev/null
./scripts/build_binary.sh
popd >/dev/null

AGENT_BIN="$REPO_ROOT/src/agent/dist/argus-agent"
if [[ ! -x "$AGENT_BIN" ]]; then
  echo "[ERROR] Agent binary not found at $AGENT_BIN" >&2
  exit 1
fi
echo "$AGENT_BIN" > "$TMP_DIR/agent_binary_path"

echo "[INFO] Writing .env with UID/GID"
cat > "$TEST_ROOT/.env" <<EOF
ARGUS_BUILD_UID=$ARGUS_BUILD_UID
ARGUS_BUILD_GID=$ARGUS_BUILD_GID
EOF

echo "[OK] Bootstrap completed"
