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

# RocketMQ NameServer returns brokerIP1 to every producer and consumer. In
# `make run` the clients are host-side `go run` processes, while Docker mode may
# still have container clients, so advertise the host LAN IP that both sides can
# dial through the compose port mapping.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
OUTPUT_PATH="${PROJECT_ROOT}/tmp/rocketmq/broker.local.conf"

detect_host_ip() {
	if [[ -n "${ROCKETMQ_BROKER_IP:-}" ]]; then
		printf '%s\n' "${ROCKETMQ_BROKER_IP}"
		return
	fi

	local iface=""
	if command -v route >/dev/null 2>&1; then
		iface="$(route -n get default 2>/dev/null | awk '/interface:/{print $2; exit}')"
	fi
	if [[ -n "${iface}" ]] && command -v ipconfig >/dev/null 2>&1; then
		ipconfig getifaddr "${iface}" 2>/dev/null && return
	fi

	if command -v ifconfig >/dev/null 2>&1; then
		ifconfig | awk '/inet / && $2 != "127.0.0.1" {print $2; exit}' && return
	fi

	printf '127.0.0.1\n'
}

broker_ip="$(detect_host_ip)"
mkdir -p "$(dirname "${OUTPUT_PATH}")"
cat > "${OUTPUT_PATH}" <<EOF
brokerClusterName = hyapp-local
brokerName = broker-a
brokerId = 0
deleteWhen = 04
fileReservedTime = 48
brokerRole = ASYNC_MASTER
flushDiskType = ASYNC_FLUSH
autoCreateTopicEnable = true
brokerIP1 = ${broker_ip}
listenPort = 10911
EOF

printf '%s\n' "${OUTPUT_PATH}"
