#!/bin/bash
set -euo pipefail

echo "[INFO] Starting proxy under supervisor..."

TEMPLATE="/etc/nginx/nginx.conf.template"
TARGET="/etc/nginx/nginx.conf"
DNS_CONF_PRIVATE="/private/argus/etc/dns.conf"
DNS_CONF_SYSTEM="/etc/resolv.conf"
DNS_DIR="/private/argus/etc"
DNS_SCRIPT="${DNS_DIR}/update-dns.sh"
RUNTIME_UID="${ARGUS_BUILD_UID:-2133}"
RUNTIME_GID="${ARGUS_BUILD_GID:-2015}"

mkdir -p "$DNS_DIR"
chown -R "$RUNTIME_UID:$RUNTIME_GID" "$DNS_DIR" 2>/dev/null || true

if [[ -x "$DNS_SCRIPT" ]]; then
  echo "[INFO] Running update-dns.sh before master starts"
  # 若脚本存在则执行，保证容器使用 bind 作为 DNS
  "$DNS_SCRIPT" || echo "[WARN] update-dns.sh execution failed"
else
  echo "[WARN] DNS update script not found or not executable: $DNS_SCRIPT"
fi

# ========== 读取 DNS ==========
if [ -f "$DNS_CONF_PRIVATE" ]; then
  echo "从 $DNS_CONF_PRIVATE 读取 DNS 服务器..."
  RESOLVERS=$(awk '/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ {print $1}' "$DNS_CONF_PRIVATE" | tr '\n' ' ')
fi

# 如果 /private 文件不存在则 fallback
if [ -z "${RESOLVERS:-}" ]; then
  echo "未在 $DNS_CONF_PRIVATE 中找到有效 DNS，使用系统 /etc/resolv.conf"
  RESOLVERS=$(awk '/^nameserver/ {print $2}' "$DNS_CONF_SYSTEM" | tr '\n' ' ')
fi

# 最后兜底：若仍为空，使用公共 DNS
if [ -z "$RESOLVERS" ]; then
  echo "警告: 未找到任何 DNS，使用默认 8.8.8.8"
  RESOLVERS="8.8.8.8"
fi

echo "检测到 DNS 服务器列表: $RESOLVERS"

# ========== 生成 nginx.conf ==========
if [ -f "$TEMPLATE" ]; then
  echo "从模板生成 nginx.conf ..."
  sed "s|__RESOLVERS__|$RESOLVERS|" "$TEMPLATE" > "$TARGET"
else
  echo "错误: 找不到 nginx.conf.template ($TEMPLATE)"
  exit 1
fi

# 打印生成结果供排查
grep resolver "$TARGET" || true

echo "[INFO] Launching nginx..."

# 启动 nginx 前台模式
exec /usr/sbin/nginx -g "daemon off;"
