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

# shellcheck source=common.sh
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/common.sh"

ensure_env_file
ensure_paths_defined

service_id() {
  compose ps -q "$1"
}

log "Verifying DNS routing via bind"

MASTER_FILE="$SYS_DEBUG_PRIVATE_CORE/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="$(tr -d '\r\n' < "$MASTER_FILE" || true)"
log "master.argus.com file content: $MASTER_IP_HOST"

BIN_ID="$(service_id bind)"
if [[ -n "$BIN_ID" ]]; then
  DIG_IP="$(docker exec "$BIN_ID" dig +short master.argus.com A | tail -n1 || true)"
  log "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" >&2
fi

for node in node-a node-b; do
  CID="$(service_id "$node")"
  if [[ -z "$CID" ]]; then
    echo "[ERR] Container for $node not found" >&2
    exit 1
  fi
  log "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)"
  log "$node resolved master.argus.com -> $RES"
done

log "DNS routing verified"
