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

TMP_ROOT="$TEST_ROOT/tmp"
ENV_FILE="$TEST_ROOT/.env"

source "$REPO_ROOT/scripts/common/build_user.sh"
load_build_user
export ARGUS_BUILD_UID ARGUS_BUILD_GID

cat > "$ENV_FILE" <<EOF
ARGUS_BUILD_UID=$ARGUS_BUILD_UID
ARGUS_BUILD_GID=$ARGUS_BUILD_GID
EOF

if [[ ! -f "$TMP_ROOT/agent_binary_path" ]]; then
  echo "[ERROR] Agent binary path missing; run 01_bootstrap.sh first" >&2
  exit 1
fi

AGENT_BINARY="$(cat "$TMP_ROOT/agent_binary_path")"
if [[ ! -x "$AGENT_BINARY" ]]; then
  echo "[ERROR] Agent binary not executable: $AGENT_BINARY" >&2
  exit 1
fi

BIND_IMAGE_TAG_VALUE="argus-bind9:latest"
if [[ -f "$TMP_ROOT/bind_image_tag" ]]; then
  BIND_IMAGE_TAG_VALUE="$(cat "$TMP_ROOT/bind_image_tag")"
fi

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

docker container rm -f argus-agent-e2e argus-agent-env-e2e argus-master-agent-e2e argus-bind-agent-e2e >/dev/null 2>&1 || true

docker network rm tests_default >/dev/null 2>&1 || true

pushd "$TEST_ROOT" >/dev/null
compose down --remove-orphans || true
BIND_IMAGE_TAG="$BIND_IMAGE_TAG_VALUE" compose up -d
popd >/dev/null

echo "[INFO] Master+Agent stack started"
