#!/bin/bash
set -euo pipefail

echo "[INFO] Starting React frontend under supervisor..."

DNS_DIR="/private/argus/etc"
DNS_SCRIPT="${DNS_DIR}/update-dns.sh"
DOMAIN=web.argus.com
WEB_DOMAIN_FILE="${DNS_DIR}/${DOMAIN}"
RUNTIME_USER="${ARGUS_RUNTIME_USER:-argus}"
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


# 记录容器 IP
IP=$(ifconfig | grep -A 1 eth0 | grep inet | awk '{print $2}' || true)
if [[ -n "${IP}" ]]; then
  echo "current IP: ${IP}"
  echo "${IP}" > "$WEB_DOMAIN_FILE"
  chown "$RUNTIME_UID:$RUNTIME_GID" "$WEB_DOMAIN_FILE" 2>/dev/null || true
else
  echo "[WARN] Failed to detect web IP via ifconfig"
fi

echo "[INFO] Launching nginx..."

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