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

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

# 直接根据 container_name 获取容器ID，避免 compose project 名称不一致导致查找失败
cid_by_name() {
  docker ps -aqf "name=^$1$"
}

echo "[INFO] Verifying DNS routing via bind..."

pushd "$TEST_ROOT" >/dev/null

# Check master IP file exists in shared private
MASTER_FILE="$TEST_ROOT/private/argus/etc/master.argus.com"
if [[ ! -f "$MASTER_FILE" ]]; then
  echo "[ERR] master.argus.com file missing at $MASTER_FILE" >&2
  exit 1
fi
MASTER_IP_HOST="$(cat "$MASTER_FILE" | tr -d '\r\n' || true)"
echo "[INFO] master.argus.com file content: ${MASTER_IP_HOST}"

# dig inside bind container
BIN_ID="$(cid_by_name argus-bind-sys)"
if [[ -n "$BIN_ID" ]]; then
  DIG_IP="$(docker exec "$BIN_ID" dig +short master.argus.com A | tail -n1 || true)"
  echo "[INFO] dig(master.argus.com) from bind container -> $DIG_IP"
  if [[ -z "$DIG_IP" ]]; then
    echo "[ERR] bind did not resolve master.argus.com" >&2; exit 1
  fi
else
  echo "[WARN] bind container not found; skip dig"
fi

for node in argus-node-a argus-node-b; do
  CID="$(cid_by_name "$node")"
  echo "[INFO] Checking resolution inside $node..."
  if ! docker exec "$CID" getent hosts master.argus.com >/dev/null 2>&1; then
    echo "[ERR] $node cannot resolve master.argus.com" >&2
    exit 1
  fi
  RES="$(docker exec "$CID" getent hosts master.argus.com | awk '{print $1}' | head -n1)"
  echo "[OK] $node resolved master.argus.com -> $RES"
done

popd >/dev/null

echo "[OK] DNS routing verified"
